Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Finding annotated classes

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65338
97
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, just getting started with annotations. Yeah, yeah, always late to the party...

Seriously, is there a way to find all classes that have been annotated with a specific annotation? For example, is there a way to find which classes have been marked with @Bear or some such?
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is very similar to the oft-asked question about finding all the classes that implement MyPluginInterface. The simple answer is no, there's no simple answer. The more complex answer is that if you control class loading, then you can know about all the loaded/loadable classes, and individually check them for the annotation you're interested in. You can do this via reflection (which will load every class you look at, perhaps not what you want) or via one of the libraries like BCEL that parse class files and "reflect" them without actually creating a Class object.

So use, for example, a URLClassLoader. Then you'll know exactly what the class path is, and you can use the java.util.jar apis to find classes in jars, and the File api to find classes not in jars, and then inspect them.

I would not be at all surprised if there exists a third party library that does all this for you automagically.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose it depends whether you want to do this at compile time or runtime, and whether it's enought to do this while using your own development tools, or you need to more general platform-independent solution. Using IntelliJ IDEA, for example, you can just right-click on an annotation and search for uages in the project. I assume something similar is possible in Eclipse as well. You may also be interested in the jdk's annotation processing tool. Or you can use reflection. With all these, you need to somehow specify the input source files or class files to be scanned (though in the case of your IDE, you've already done that). I'm not sure which of these approaches might be closest to what you're looking for.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic