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.");
}
}
运行结果:

该博客主要展示了如何使用Java动态代理(Proxy)实现方法调用的前后增强功能。通过创建InvocationHandler并结合Proxy.newProxyInstance(),可以在目标方法执行前后插入自定义逻辑,例如添加日志或验证操作。示例中定义了一个接口INeedAgent,一个其实现类NeedAgentImpl,以及一个代理类MyProxy,MyProxy的getProxy()方法用于生成代理对象。在代理对象调用doTest()方法时,会先执行beforeInvoke(),然后执行实际的方法,最后调用afterInvoke()。这个例子为理解Java动态代理提供了一个简单的应用场景。
477

被折叠的 条评论
为什么被折叠?



