创建一个代理处理类
public class ProxyInvocationHandler<T> implements InvocationHandler {
private T target;
public void setTarget(T target) {
this.target = target;
}
public T getProxy() {
return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),
this.target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(this.target, args);
return invoke;
}
}
使用代理
public class Test {
public static void main(String[] args) {
IUser user = new UserImpl();
ProxyInvocationHandler<IUser> pih = new ProxyInvocationHandler<>();
pih.setTarget(user);
IUser proxy = pih.getProxy();
proxy.getInfo();
proxy.getName();
}
}