大家好。
我想通过这样调用在调用的方法上添加一个监听器:
myClass.myMethod(...);
在运行时,它会是这样的:
listenerClass.beforeMethod(...);
myClass.myMethod(...);
listenerClass.beforeMethod(...);
我想覆盖 Method.invoke(...)
:
public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
doBefore(...);
super.invoke(...);
doAfter(...);
}
Class.java 和 Method.java 是最终的,我尝试使用我自己的 ClassLoader。 也许工厂或注释可以完成这项工作。 感谢您的回答。
最佳答案
一种选择是使用面向方面的编程模式。
在这种情况下,您可以使用代理(JDK 或 CGLIB)。
这是一个使用 JDK 代理的示例。你需要一个接口(interface)
interface MyInterface {
public void myMethod();
}
class MyClass implements MyInterface {
public void myMethod() {
System.out.println("myMethod");
}
}
...
public static void main(String[] args) throws Exception {
MyClass myClass = new MyClass();
MyInterface instance = (MyInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[] { MyInterface.class }, new InvocationHandler() {
MyClass target = myClass;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("myMethod")) { // or some other logic
System.out.println("before");
Object returnValue = method.invoke(target, args);
System.out.println("after");
return returnValue;
}
return method.invoke(target);
}
});
instance.myMethod();
}
打印
before
myMethod
after
显然,有些库在这方面做得比上面的要好得多。看看 Spring AOP 和 AspectJ。
关于java - Method.invoke java 上的监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27233276/