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

前端 未结 3 1046
旧时难觅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: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.

提交回复
热议问题