import java.lang.reflect.*;
public class JDKProxySupport implements InvocationHandler {
private Object targetObj, proxyObj;
public JDKProxySupport() {
}
public JDKProxySupport(Object target) {
targetObj = target;
// 生成代理
proxyObj = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("在方法之前做了点事情");
Object obj = method.invoke(targetObj, args);
System.out.println("在方法之后做了点事情");
return obj;
}
public Object getProxyObj() {
return proxyObj;
}
public static void main(String[] args) {
JDKProxySupport ps = new JDKProxySupport(new TestProxy());
TestProxyInterface test = (TestProxyInterface) ps.getProxyObj();
test.doSomething();
}
}