Search code examples
javareflectionannotations

instantiate a class that contains an annotation


can I use the reflection API to find a class according to an annotation? I'm looking for a way to execute a class based on an annotation. for example, I have a class credentials with an Verify annotation and the parameter "token" and "permissions" are actions to execute the responsable class

@Verify ("token")
@Verify ("permissions")
class Credentials {
....
}

The Verify("token") should call the execute method in the TokenVerifier class and the Verify("permissions") should call the execute method in the PermissionsVerifier class, for example. I would put in my classes the annotation @verifier with the necessary parameters to be able to find it. Like this:

@verifier(path="classPath", action="token")
class TokenVerifier
{
…
 }

 @verifier(path="classPath", action="permissions")
 class PermissionsVerifier
 {
 …
 }

Can I get somehow those classes with these annotations? It is worth mentioning that I do not know which classes will have these annotations, the idea is that it is dynamic.


Solution

  • Standard Java does not allow you to find all classes with a given annotation, since annotations are evaluated after loading a class, not before.

    However there are tools that scan the classpath for classes containing an annotation and loading the class if a match occurs, e.g. fast-classpath-scanner.

    To get all Verifys:

    new FastClasspathScanner("package.to.search.in")
        .matchClassesWithAnnotation(Verify.class, c -> System.out.println(c.getName()))
        .scan();
    

    To get all verifiers:

    new FastClasspathScanner("package.to.search.in")
        .matchClassesWithAnnotation(verifier.class, c -> System.out.println(c.getName()))
        .scan();
    

    After loading the classes you can evaluate and match the classes as you like with standard reflection.