有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取注释元素的默认值?

假设我有一个注释

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    int value() default 1;
}

是否有任何方法可以使用反射或其他方法获得1的值


共 (2) 个答案

  1. # 1 楼答案

    是的,你可以使用^{}

    Returns the default value for the annotation member represented by this Method instance.

    以下面的例子为例

    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
    
  2. # 2 楼答案

    怎么样

    MyAnnotation.class.getMethod("value").getDefaultValue()