Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all classes on the classpath that have a specific method annotation?

I want to implement an intialization mechanism that is annotation-based in Java. Specifically, I have an annotation I've defined:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Initialization {

/**
 * If the eager initialization flag is set to <code>true</code> then the
 * initialized class will be initialized the first time it is created.
 * Otherwise, it will be initialized the first time it is used.
 * 
 * @return <code>true</code> if the initialization method should be called
 *         eagerly
 */
boolean eager() default false;

}

Additionally, I have an interface:

public interface SomeKindOfBasicInterface {}

I want to find every implementation of the SomeKindOfBasicInterface class on my classpath that has the @Initialization annotation on a method. I'm looking at Spring's MetaDataReader tools, which look like the best way to defer loading the other SomeKindOfBasicInterface implementations while I'm doing this... but I'm not sure how to do a search like I'm describing. Any tips?

like image 950
Chris R Avatar asked Mar 18 '09 17:03

Chris R


People also ask

How do I list all classes in a classpath?

You can use File#listFiles() to get a list of all files in the given directory: for (File file : root. listFiles()) { // ... }

How do you check if a class has an annotation?

The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation. If the return value is false , then the class object is not an annotation.

Can you find all classes in a package using reflection?

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes. The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

How can you directly access all classes in the package in Java?

Since Java enforces the most restrictive access, we have to explicitly declare packages using the export or open module declaration to get reflective access to the classes inside the module.


1 Answers

You could use Reflections, which is a Java runtime metadata analysis tool. I've used it to get all subtypes of a given type, but it can handle your case as well.

like image 165
Kaitsu Avatar answered Oct 23 '22 09:10

Kaitsu