Java: How to listen on methods invocation without registering each object explicitely?

前端 未结 3 996
旧时难觅i
旧时难觅i 2021-01-26 11:42

I want to listen on method calls in order to attach additional behavior dynamically around the call. I\'ve already done it on JUnit methods with a custom annotation and runner.

相关标签:
3条回答
  • 2021-01-26 12:22

    Well,this is commonly seen with Spring Framework and Aspect Oriented Programming. Since you delegate your constructor calls to Spring, it is quite easy for Spring to put a proxy in place to intercept calls to the actual objects.

    As far as I can tell, the only way to intercept calls is to use a proxy. Either in the way you mentioned or using Spring and AOP.

    0 讨论(0)
  • 2021-01-26 12:28

    As far as I know there is no easy way to intercept method calls that are called on a concrete class. As mentioned you could manipulate the bytecode during compilation (as Used in AOP) or at class loading time (as used from cglib). Another product to instrument Classes would be jmockit (http://jmockit.org/). Usually I would use this special kind of black magic only in testing environments and not in an productive environment.

    Another way you could go is Annotation Processing. It work's during compiling process. You have to write a Processor which will walk through your source code and generate source-code that contains the original code plus the enhanced method-calls you need. Depending on how much source-code you have to enhance, this method might be a good idea, but in general it is a lot of work. Here's a link (https://deors.wordpress.com/2011/10/08/annotation-processors/). Despite usually it's used in combination with annotations, this is not a strict requirement.

    0 讨论(0)
  • 2021-01-26 12:34

    I think cglib let you instrument concrete classes.

    0 讨论(0)
提交回复
热议问题