1、動態(tài)代理的接口
package cn.proxy;
public interface ProxyInterface {
public void doSomething();
}
2、實現(xiàn)類
package cn.proxy;
public class ProxyImpl implements ProxyInterface {
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("實現(xiàn)類");
}
}
3、要實現(xiàn)代理的類
package cn.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler{
private Object object; ?//傳入一個Object類型的對象,給該類中的invoke方法調(diào)用
public ProxyHandler() {
// TODO Auto-generated constructor stub
}
public ProxyHandler(Object object) {
this.object = object;
}
/**
* ? ?proxy:被代理的實現(xiàn)類
* ? ?method:被代理的接口
* ? ?args:參數(shù),代理后的類
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("執(zhí)行動態(tài)代理前!");
Object result = method.invoke(object, args);
System.out.println("執(zhí)行動態(tài)代理后!");
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、測試結(jié)果
實現(xiàn)類
執(zhí)行動態(tài)代理前!
實現(xiàn)類
執(zhí)行動態(tài)代理后!
6、背后的原理