方法上的侦听器。调用java

方法上的侦听器。调用java,java,reflection,listener,Java,Reflection,Listener,大家好。 我想通过如下方式调用在调用的方法上添加侦听器: myClass.myMethod(...); 在运行时,它将类似于: listenerClass.beforeMethod(...); myClass.myMethod(...); listenerClass.beforeMethod(...); 我想重写方法。调用(…): public Object invoke(Object obj, Object... args) throws IllegalAccessException,

大家好。
我想通过如下方式调用在调用的方法上添加侦听器:

myClass.myMethod(...);
在运行时,它将类似于:

listenerClass.beforeMethod(...);
myClass.myMethod(...); 
listenerClass.beforeMethod(...);
我想重写
方法。调用(…)

public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    doBefore(...);
    super.invoke(...);
    doAfter(...);
}
java和Method.java是最终版本,我尝试使用自己的类加载器。 也许工厂或注释可以完成这项工作。
谢谢您的回答。

一个选择是使用面向方面的编程模式

在这种情况下,您可以使用代理(JDK或CGLIB)

下面是一个使用JDK代理的示例。你需要一个接口

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();
}

显然,有些库在这方面做得比上面的好得多。看一看Spring AOP和AspectJ。

请花点时间阅读帮助中心关于如何格式化您的帖子。另一种方法是使用字节码注入和类库或@Lolo优秀链接,谢谢分享。你知道类似的C/C++库吗?
before
myMethod
after