标签:throw object ace ade ati targe tin set turn
public class ProxyInvocationHandler implements InvocationHandler {
//代理谁
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//调用代理程序的执行方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result=method.invoke(target,args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
public class Client {
public static void main(String[] args) {
//被代理对象,真实角色
UserServiceImpl userService=new UserServiceImpl();
//代理角色,不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//设置需要代理的对象
pih.setTarget(userService);
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
标签:throw object ace ade ati targe tin set turn
原文地址:https://www.cnblogs.com/yeyu2000/p/14814305.html