Alon
Alon

Reputation: 753

Retrieve annotation by name

I know it's possible to get a class by name, using

public String className = "someName";
public Class<?> c = Class.forName(className);

Is it possible to retrieve an annotation by name? I tried this:

public String annotationName = "someName";
public Class<?> c = Class.forName(annotationName);

And then casting c to Class<? extends Annotation>, which works, but I get an Unchecked cast warning.

I also tried

public String annotationName = "someName";
public Class<? extends Annotation> c = Class.forName(annotationName);

But when I do that I get the error

Incompatible types.
Required: Class<? extends java.lang.annotation.Annotation>
Found: Class<Capture<?>>

Upvotes: 2

Views: 715

Answers (1)

Holger
Holger

Reputation: 298103

Use asSubclass. Unlike compiler generated type casts, which can only work with types known at compile-time, this will perform a check against the Class object retrieved at runtime. Since this is safe, it won’t generated an “Unchecked cast” warning. Note the existence of a similar operation, cast for casting an instance of a Class. These methods were added in Java 5, specifically to aid code using Generics.

String annotationName = "java.lang.Deprecated";
Class<? extends Annotation> c = Class.forName(annotationName).asSubclass(Annotation.class);
boolean depr = Thread.class.getMethod("stop").isAnnotationPresent(c);
System.out.println(depr);

Upvotes: 3

Related Questions