package com.gong.demo04;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocation 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 {
return method.invoke(target,args);
}
}
测试 如何使用接口:
package com.gong.demo04;
import com.gong.demo02.userService;
import com.gong.demo02.userServiceImpl;
public class client {
public static void main(String[] args) {
//真实角色 就是实现了接口的角色
userService userService = new userServiceImpl();
//代理角色 现在不存在
ProxyInvocation proxyInvocation = new ProxyInvocation();
proxyInvocation.setTarget(userService); //将接口设置进去
userService proxy =(com.gong.demo02.userService) proxyInvocation.getProxy();
proxy.add();
}
}