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?
You can use File#listFiles() to get a list of all files in the given directory: for (File file : root. listFiles()) { // ... }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With