JDK动态代理Demo需要几样东西:
- 被代理类
- 被代理类实现的接口
- 代理类
- 测试类
被代理类实现的接口
package java_jdk_proxy;
public interface Person {
public void say();
public void eat();
}
被代理类
package java_jdk_proxy;
public class PersonImpl implements Person {
@Override
public void say() {
System.out.println("person say .. ");
}
@Override
public void eat() {
System.out.println("person eat .. ");
}
}
代理类
package java_jdk_proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler {
public Object target; // 被代理对象
public ProxyHandler(Object tar) {
this.target = tar;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("befor proxy..");
Object result = method.invoke(target, args);
System.out.println("after proxy..");
System.out.println("============");
return result;
}
}
测试类
package java_jdk_proxy;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
PersonImpl personImpl = new PersonImpl();
ProxyHandler handler = new ProxyHandler(personImpl);
Person proxy = (Person) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), PersonImpl.class.getInterfaces(), handler);
proxy.say();
proxy.eat();
}
}
运行结果
befor proxy..
person say ..
after proxy..
============
befor proxy..
person eat ..
after proxy..
============
总结:JDK动态代理是接口动态代理,被代理类需要实现接口,且只有接口中存在的方法才可以被代理.通过classloader来加载代理类的字节码,使用反射最终执行被代理类的被代理方法.
ps:因为是使用的反射机制执行,所以在性能上不高.