-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventTracer.java
73 lines (65 loc) · 2.3 KB
/
EventTracer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package eventTracer;
import java.awt.*;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Cay Horstmann
* @version 1.31 2004-05-10
*/
public class EventTracer {
private InvocationHandler handler;
public EventTracer() {
// the handler for all event proxies
handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method + "" + args[0]);
return null;
}
};
}
/**
* Adds event tracers for all events to which this component and its children can listen
*
* @param c a component
*/
public void add(Component c) {
// get all events to which this component can listen
try {
BeanInfo info = Introspector.getBeanInfo(c.getClass());
EventSetDescriptor[] eventSets = info.getEventSetDescriptors();
for (EventSetDescriptor eventSet : eventSets)
addListener(c, eventSet);
} catch (IntrospectionException ignored) {
}
// ok not to add listeners if exception is thrown
if (c instanceof Container) {
// get all children and call add recursively
for (Component comp : ((Container) c).getComponents())
add(comp);
}
}
/**
* Add a listener to the given event set
*
* @param c a component
* @param eventSet a descriptor of a listener interface
*/
private 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 ignored) {
}
// ok not to add listener if exception is thrown
}
}