ackage liu.dh.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Demo8_GetProxy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PostBank pBanks = new PostBank();
Bank1 nBank1 = (Bank1)getProxyInstance(pBanks);
nBank1.save();
nBank1.qurey();
}
//动态创建代理对象,在被代理对象创建时,创建
public static Object getProxyInstance(PostBank pBank){
MyHandler mHandler = new MyHandler(pBank);
return Proxy.newProxyInstance(pBank.getClass().getClassLoader(),
pBank.getClass(). getInterfaces(), mHandler);
}
}
class MyHandler implements InvocationHandler{
private Object target;
public MyHandler(Object target){
this.target = target;
}
@Override
//实现InvocationHandler,通过调用处理程序实现被代理对象调用方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
Object object = null;
////通过invoke()方法传入被代理类对象,调用其方法
object= method.invoke(target);//没有形式参数可以不写
return object;
}
}
|
|