demo:
/**
* 2021年6月2日上午10:25:36
*/
package testProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author XWF
*
*/
public class TestProxy {
/**
* @param args
*/
public static void main(String[] args) {
INeedAgent a = new NeedAgentImpl();
INeedAgent proxy = MyProxy.getProxy(a);
proxy.doTest("TEST");
}
}
interface INeedAgent {
public void doTest(String str);
}
class NeedAgentImpl implements INeedAgent {
@Override
public void doTest(String str) {
System.out.println("doTest:" + str);
}
}
class MyProxy {
@SuppressWarnings("unchecked")
public static <T> T getProxy(T obj) {
return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforeInvoke();
Object result = method.invoke(obj, args);
afterInvoke();
return result;
}
});
}
private static void beforeInvoke() {
System.out.println("before invoke.");
}
private static void afterInvoke() {
System.out.println("after invoke.");
}
}
运行结果: