我们说我有一个注释。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value() default 1;
}
有没有办法使用反射或其他东西来获取1
的值?
答案 0 :(得分:3)
怎么样
MyAnnotation.class.getMethod("value").getDefaultValue()
答案 1 :(得分:2)
是的,您可以使用Method#getDefaultValue()
返回此
Method
实例所代表的注释成员的默认值。
采取以下示例
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;
}
打印
42
1