Reputation: 3802
How can i print the Annotation values for different Annotation?
I have the following two Annotation
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Author
{
String name() default "--Unknown--";
String date() default "--Unknown--";
}
and
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Revision
{
int version() default 0;
String modifiedBy() default "--Unknown--";
}
now one class use both this annotations, and inside this class I want to display the annotation values for both the annotations
@Author(
name = "Panther",
date = "22.04.2013"
)
@Revision(
version = 2,
modifiedBy = "Black",
)
public class AnnotationTest
{
public static void main(String[] args)
{
AnnotationTest b = new AnnotationTest();
for(Annotation a : AnnotationTest.class.getDeclaredAnnotations())
{
// for Author display name and date
// for revision display version and modifiedBy
}
}
}
is there any way to do that?
Upvotes: 2
Views: 481
Reputation: 159754
You can use instanceof
:
for (Annotation a : AnnotationTest.class.getDeclaredAnnotations()) {
if (a instanceof Author) {
Author author = (Author) a;
System.out.println("Author Name: " + author.name());
System.out.println("Date: " + author.date());
} else if (a instanceof Revision) {
Revision revision = (Revision) a;
System.out.println("Version: " + revision.version());
System.out.println("Modified By: " + revision.modifiedBy());
}
}
Upvotes: 3
Reputation: 2769
the answer is very simple:
a.getClass().getAnnotation(Author.class).name();
this is generic, so getAnnotation will return the type you asked for, then you can get the fields directly.
Upvotes: 1