动态代理

来源:互联网 发布:写文章的软件 编辑:程序博客网 时间:2024/05/23 10:23
动态代理参数:
Object proxy Obj = Proxy.newProxyInstance(参数1,参数2,参数3);
参数1:ClassLoader,负责将动态创建类,加载到内存。当前类.class.getClassLoader();
参数2:Class[] interfaces ,代理类需要实现的所有接口(确定方法),被代理类实例.getClass().getInterfaces(); 
参数3:InvocationHandler, 请求处理类,代理类不具有任何功能,代理类的每一个方法执行时,调用处理类invoke方法。
voke(Object proxy ,Method ,Object[] args) 
参数1:代理实例
参数2:当前执行的方法

参数3:方法实际参数。



主函数

public class Test {
public static void main(String[] args) {
//创建被代理对象
final FruitImpl fi = new FruitImpl();
//创建动态代理对象
Fruit f = (Fruit)Proxy.newProxyInstance(fi.getClass().getClassLoader(), 
fi.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("选择水果...");
//执行被代理对象的方法
Object invoke = method.invoke(fi, null);
System.out.println("添加水果成功...");
return invoke;
}
});
f.addFruit();
}
}


//接口
public interface Fruit {
public void addFruit();


}


public class FruitImpl implements Fruit{
@Override
public void addFruit() {
System.out.println("添加水果..");
}
}