File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Finding annotated classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finding annotated classes" Watch "Finding annotated classes" New topic

Finding annotated classes

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63848

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?

[Asking smart questions] [About Bear] [Books by Bear]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15302

GenRocket - Experts at Building Test Data
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Finding annotated classes
It's not a secret anymore!