动态生成代理
package com.sangeng.Dem03;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyinvocationHangler 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);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target,args);
return result;
}
}
客户调用类
package com.sangeng.Dem03;
public class Client {
public static void main(String[] args) {
//真实角色
Userserviceimpl userservice = new Userserviceimpl();
//代理角色,不存在
ProxyinvocationHangler pih =new ProxyinvocationHangler();
//设置要代理的对象
pih.setTarget(userservice);
//动态生成代理类
Userservice proxy = (Userservice)pih.getProxy();
proxy.add();
}
}