proxy动态代理
* 真实对象:定义目标操作* @author WalkingDog
*
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("RealSubject.doSomething");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler {
private Object object;
public DynamicProxy(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Before Invoke ! method : " + method);
//我们可以再代理方法调用前后添加功能
Object result = method.invoke(object, args);
System.out.println("object : " + object + "\tresult : " + result + "\targs : " + args);
System.out.println("After Invoke !");
return result;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* 客户端
* @author WalkingDog
*
*/
public class Client {
public static void main(String[] args) throws Exception {
//创建目标对象,也就是被代理对象
RealSubject realSubject = new RealSubject();
//将目标对象交给代理
InvocationHandler handler = new DynamicProxy(realSubject);
// Class<?> proxyClass = Proxy.getProxyClass(Subject.class.getClassLoader()
// , new Class[]{Subject.class});
// Subject subject = (Subject)proxyClass.getConstructor(new Class[]{InvocationHandler.class})
// .newInstance(new Object[]{handler});
//返回代理对象,相当于上面两句
Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
realSubject.getClass().getInterfaces(),
handler();
//叫代理对象去doSomething(),其实在代理对象中的doSomething()中还是会
//用handler来调用invoke(proxy, method, args) 参数proxy为调用者subject(this),
//method为doSomething(),参数为方法要传入的参数,这里没有
subject.doSomething();
}
}