先上一小段 Toy Code
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxy<T> implements InvocationHandler {
private T target;
public JdkProxy(T target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("log something...");
Object result = method.invoke(target, args);
System.out.println("do something...");
return result;
}
public static void main(String[] args) {
IService proxy = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(),
new Class<?>[] { IService.class }, new JdkProxy<IService>(new Service()));
proxy.say("jack");
}
}
运行结果
log something...
hello jack
do something...
下面就 jdk动态代理是怎么实现的、动态代理的功能目的稍微分析下:
...