不理解动态代理的两句代码:
Proxy.newProxyInstance(subject.getClass().getClassLoader(),
subject.getClass().getInterfaces(),proxy);
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {}
package 动态代理设计模式;
import java.lang.reflect.Proxy;
public class mainTest {
public static void main(String[] args) {
Subject subject=new SuperMan();
动态代理设计模式.Proxy proxy=new 动态代理设计模式.Proxy(subject);
//动态创建一个代理对象(类加载器)
Subject s=(Subject) Proxy.newProxyInstance(subject.getClass().getClassLoader(), subject.getClass().getInterfaces(),proxy);
s.shopping();
}
}
package 动态代理设计模式;
public interface Subject {
public void shopping();
}
package 动态代理设计模式;
public class SuperMan implements Subject{
@Override
public void shopping() {
// TODO Auto-generated method stub
System.out.println("给媳妇买化妆品!");
}
}
package 动态代理设计模式;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//代理类
public class Proxy implements InvocationHandler {
private Subject target;
public Proxy(Subject target) {
this.target=target;
}
@Override//参数(代理类,被代理的方法,被代理的方法的参数组)
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("做大量的商品专业评估");
method.invoke(target, args);//被代理人真正的业务
//代购之后要做的事情
System.out.println("代购之后的客户满意度调查");
return null;
}
}