Reputation: 21978
Let's say I have an Annotation.
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value() default 1;
}
Is there any way to get the value of 1
using reflection or something?
Upvotes: 4
Views: 2309
Reputation: 279960
Yes, you can use Method#getDefaultValue()
which
Returns the default value for the annotation member represented by this
Method
instance.
Take the following example
public class Example {
public static void main(String[] args) throws Exception {
Method method = Example.class.getMethod("method");
MyAnnotation annot = method.getAnnotation(MyAnnotation.class);
System.out.println(annot.value()); // the value of the attribute for this method annotation
Method value = MyAnnotation.class.getMethod("value");
System.out.println(value.getDefaultValue()); // the default value
}
@MyAnnotation(42)
public static void method() {
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
int value() default 1;
}
it prints
42
1
Upvotes: 2
Reputation: 124225
How about
MyAnnotation.class.getMethod("value").getDefaultValue()
Upvotes: 5