package liu.dh.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Demo7_GetProxy {
/**
* @param args
* 动态代理: interface Bank1,被代理类:PostBank;
* newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建被代理类对象
PostBank pstBank = new PostBank();
pstBank.save();
pstBank.qurey();
System.out.println("----------");
//创建程序调用对象
MyInvocationHandler mHandler = new MyInvocationHandler(pstBank);
//创建代理类实例,使用接口向下转型
Bank1 pb = (Bank1)Proxy.newProxyInstance(pstBank.getClass().getClassLoader(),
pstBank.getClass().getInterfaces(), mHandler);
pb.save();
pb.qurey();
}
}
//首先实现InvocationHandler接口,通过invoke()方法传入被代理类对象
class MyInvocationHandler implements InvocationHandler{
private Object target;
public MyInvocationHandler(Object target){
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
//通过invoke()方法传入被代理类对象
Object object = null;
System.out.println("客户当前金额");
object = method.invoke(target);
System.out.println("客户查询记录");
return object;
}
}
|
|