2
比方說,我有一個註釋。如何獲取註釋元素的默認值?
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value() default 1;
}
有沒有辦法使用反射或東西拿到1
價值?
比方說,我有一個註釋。如何獲取註釋元素的默認值?
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value() default 1;
}
有沒有辦法使用反射或東西拿到1
價值?
如何
MyAnnotation.class.getMethod("value").getDefaultValue()
是的,你可以使用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