开发者

Intercepting annotated method calls without AOP

开发者 https://www.devze.com 2023-04-07 15:56 出处:网络
Is it possible to intercept the execution of a method that 开发者_如何学Pythonis annotated with a custom annotation without using any AOP framework such as AspectJ, Spring AOP, Guice, etc... I\'m curi

Is it possible to intercept the execution of a method that 开发者_如何学Pythonis annotated with a custom annotation without using any AOP framework such as AspectJ, Spring AOP, Guice, etc... I'm curious to find out if any of the default java apis can be used for this purpose (such as Reflection).

Thanks.


You cannot directly intercept method calls of existing methods without hooking into e.g., instantiation logic. One approach is to separate instantiation logic into a factory which can employ e.g., a Proxy.

public class FooFactry() {
     private InvocationHandler handler;

     public FooFactory(InvocationHandler handler) {
         this.handler = handler;
     }

     public Foo newInstance() {
        return (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                              new Class[] { Foo.class },
                              handler);
     }
}

You can use a custom InvocationHandler to intercept any method issued on Foo. You could also create your own wrapper to avoid dynamic proxies, class FooWrapper extends Foo{} to achieve the same result.


You can use reflection to invoke methods, but you can't use it to intercept method invocations. Likewise, you can create Proxies with dynamic invocation handlers with the Proxy class, but you can't intercept existing code that doesn't target a proxy.

So the answer is no.


It cannot be done using reflection because does not provide any control over execution. But you can write your own agent. You would need to instrument classes, which might be easier using something like BCEL. It is very much with the Java framework and kosher.

0

精彩评论

暂无评论...
验证码 换一张
取 消