-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSimpleDynamicProxy.java
More file actions
44 lines (37 loc) · 1.43 KB
/
SimpleDynamicProxy.java
File metadata and controls
44 lines (37 loc) · 1.43 KB
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
package thinkinginjava.typeinfo;
import java.lang.reflect.*;
/*
* InvocationHandler is the interface implemented by the invocation handler of a proxy instance.
* Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance,
* the method invocation is encoded and dispatched to the invoke method of its invocation handler.
*/
class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("**** proxy: " + proxy.getClass() + ", method: "
+ method + ", args: " + args);
if (args != null)
for (Object arg : args)
System.out.println(" " + arg);
return method.invoke(proxied, args);
}
}
class SimpleDynamicProxy {
public static void consumer(Interface iface) {
iface.doSomething();
iface.somethingElse("bonobo");
}
public static void main(String[] args) {
RealObject real = new RealObject();
consumer(real);
// Insert a proxy and call again:
Interface proxy = (Interface) Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[]{Interface.class}, new DynamicProxyHandler(real));
consumer(proxy);
}
}