0%

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
// 定义接口
public interface HelloInterface {
void sayHello();
}

// 实现接口
public class Hello implements HelloInterface {
public void sayHello() {
System.out.println("Hello");
}
}

// 构建一个handler类来实现InvocationHandler接口
public class ProxyHandler implements InvocationHandler{
private Object object;
public ProxyHandler(Object object){
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoke " + method.getName());
method.invoke(object, args);
System.out.println("After invoke " + method.getName());
return null;
}
}

public class demo {
public static void main(String[] args) {
HelloInterface hello = new Hello();

HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(
hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(),
new ProxyHandler(hello)
);

proxyHello.sayHello();
}
}

// 匿名内部类实现
public class demo {
public static void main(String[] args) {

final Hello hello = new Hello();

HelloInterface proxyInstance = (HelloInterface) Proxy.newProxyInstance(
hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoke " + method.getName());
method.invoke(hello, args);
System.out.println("After invoke " + method.getName());
return null;
}
});
proxyInstance.sayHello();
}
}