Issue
I'm implementing an annotation processor that needs all classes that implement an interface.
The main issue is that these classes can be anywhere, so there isn't an easy way to get them.
I cannot edit this classes in any way.
I need to get this classes to generate a Map.
How can I achieve this?
Thanks
Solution
Depends on your definition of 'all classes that implement an interface'.
Just the ones that are being compiled right now
This is trickier than it looks like. Compilation is often incremental, meaning, even if you run a build that says 'compile everything', only those source files that actually need to be recompiled (because their source file has a more recent modification timestamp than the class files that spin off from it and it doesn't reference anything from sources that are marked for recompilation). So, 'being compiled right now' is a smaller batch of files than you think.
To do this, it's easy. First, register yourself for the annotation "*"
, which means, you want to trigger on every source file, annotated or not: @SupportedAnnotationTypes("*")
.
Next, in your process
method, you can ask the RoundEnv
for all classes. Go through them, check what interfaces they implement, and process everything that implements what you wanted.
Everything from my project
This is impossible. Classpath as a concept doesn't have a 'list' abstraction, therefore, you can't just 'get everything that implements X'.
What you can do, is spit out a textfile as part of your annotation processing, which lists the source file of everything that is relevant. You can then use the Filer during the final round (where process
is called with a roundEnv
indicating it is the final one) to read this text file (the classpath does have the concept of 'give me the resource named FOO'), then you ask the filer for each of the source (or class, whatever way you want to go) file and check if they still exist. If yes, then at least you know it hasn't changed at all. If it doesn't, then the programmer deleted it and you should act accordingly.
This is somewhat complicated and I'm not aware of any frameworks. You'll have to build it yourself.
All classes anywhere on any machine anywhere in time or space.
Yeah, well. Not possible, duh.
Answered By - rzwitserloot
Answer Checked By - Candace Johnson (JavaFixing Volunteer)