How to build a list of classes annotated with my custom annotation?

后端 未结 8 1141
梦毁少年i
梦毁少年i 2020-12-23 16:52

I want to get a complete list of classes in the application which are annotated with @Custom annotation. What is the best mechanism for this operation?

相关标签:
8条回答
  • 2020-12-23 17:36

    Run a find in your IDE on the source, If you trying to do this on compiled classes you would have add a method to them to support this, even if you decompiled the classes I do not think annotations or comments would show up.

    0 讨论(0)
  • 2020-12-23 17:38

    As you probably know by now, Java has no way to enumerate all packages or the classes in each package. So you have to do it the "hard" way. Options:

    1. Use a tool like grep to search for the annotation. Advantage: Fast, simple. Drawbacks: Might return false positives (like classes where the annotation is commented out).

    2. Compile the code and process the result with javap. That works on the bytecode level[*]. It gives you accurate results but the output of javap isn't really meant for automatic processing.

    3. Use a bytecode library like ASM. Not for the faint of heart but it allows you to access other data as well (like implemented interfaces, fields, etc) in relation to the annotation.

    4. Last option: Eclipse uses its own Java compiler which can build an AST from Java code (even if the code doesn't compile). Advantage over ASM: You get a model for Java code for free. Makes certain operations more simple. No so easy to set up, though. See my blog for an example.

    [*]: The annotation must have Retention.RUNTIME for this to work.

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