1、动态代理的接口
package cn.proxy;
public interface ProxyInterface {
public void doSomething();
}
2、实现类
package cn.proxy;
public class ProxyImpl implements ProxyInterface {
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("实现类");
}
}
3、要实现代理的类
package cn.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler{
private Object object; //传入一个Object类型的对象,给该类中的invoke方法调用
public ProxyHandler() {
// TODO Auto-generated constructor stub
}
public ProxyHandler(Object object) {
this.object = object;
}
/**
* proxy:被代理的实现类
* method:被代理的接口
* args:参数,代理后的类
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("执行动态代理前!");
Object result = method.invoke(object, args);
System.out.println("执行动态代理后!");
return result;
}
//获取代理后的对象
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), object.getClass().getInterfaces(), this);
}
}
4、测试类
package cn.proxy;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
ProxyInterface proxyInterface = new ProxyImpl();
proxyInterface.doSomething();
ProxyHandler proxyHandler = new ProxyHandler(proxyInterface);
ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(proxyInterface.getClass().getClassLoader(), proxyInterface.getClass().getInterfaces(), proxyHandler);
proxy.doSomething();
}
}
5、测试结果
实现类
执行动态代理前!
实现类
执行动态代理后!
6、背后的原理
网友评论