java 利用反射调试GUI

简介

java核心编程个出的代码只要通过
EventTrace tracer = new EventTracer();
tracer.add(frame)
就可以跟踪事件了

code

/*
 * @Author: your name
 * @Date: 2020-11-08 16:41:50
 * @LastEditTime: 2020-11-08 17:05:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /java/calcu/EventTracer.java
 */
package calcu;

import java.awt.*;
import java.beans.*;
import java.lang.reflect.*;

public class EventTracer {
    private InvocationHandler handler;

    public EventTracer() {
        // the handler for all event proxies
        handler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) {
                System.out.println(method + ": " + args[0]);
                return null;
            }
        };
    }

    public void add(Component c) {
        try {
            // get all events to which this component can listen
            BeanInfo info = Introspector.getBeanInfo(c.getClass());

            EventSetDescriptor[] eventSets = info.getEventSetDescriptors();
            for (EventSetDescriptor eventSet : eventSets) {
                addListener(c, eventSet);
            }
        } catch (IntrospectionException e) {

        }

        if (c instanceof Container) {
            // get all children and call add recursively
            for (Component comp : ((Container) c).getComponents())
                add(comp);
        }
    }

    public void addListener(Component c, EventSetDescriptor eventSet) {
        // make proxy object for this listener type and route all calls to the handler
        Object proxy = Proxy.newProxyInstance(null, new Class[] { eventSet.getListenerType() }, handler);

        // add the proxy as a listener to the component
        Method addListenerMethod = eventSet.getAddListenerMethod();
        try {
            addListenerMethod.invoke(c, proxy);
        } catch (ReflectiveOperationException e) {

        }
    }
}

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/13944922.html