1
2
3
public interface HelloWorld {
public void sayHelloWorld();
}
1
2
3
4
5
6
7
public class HelloWorldImpl implements HelloWorld {

@Override
public void sayHelloWorld() {
System.out.println(">>>>>HelloWorld!<<<<<")
}
}

动态代理的思路:

  1. 建立代理对象和真实对象之间的关系: bind;
  2. 实现代理逻辑: invoke;

实现代理逻辑类必须实现java.lang.reflect.InvocationHandler接口;

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
public class JdkProxyExample implements InvocationHandler {

// real object
private Object target = null;

/*
relation: proxy object -> true object
@param target: true object
@return proxy object
*/
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}

/*
proxy method logics
@param proxy: proxy object
@param method: current invoked method
@param args: current method args
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxy logics method");
System.out.println("setUp service before true object");
Object obj = method.invoke(target, args); // <=> sayHelloWorld
System.out.println("tearDown service after true object");
return obj;
}
}

测试JDK动态代理:

1
2
3
4
5
public void testJdkProxy() {
JdkProxyExample jdk = new JdkProxyExample();
HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImpl());
proxy.sayHelloWorld();
}

Output:

1
2
3
4
proxy logics method
setUp service before true object
>>>>>HelloWorld!<<<<<
tearDown service after true object