【问题标题】:Java override annotation's default valueJava 覆盖注解的默认值
【发布时间】:2016-02-02 03:52:29
【问题描述】:

我有一个跨多个项目共享的 jar 库,该库的目的是将带注释的字段转换为 stringify API 响应。

public @interface MyField {
   ...
   String dateFormat() default "dd/MM/yyyy";
   ...
}

使用它:

@MyField
private String myDate;

问题是当项目使用不同的日期格式(例如 yyyy/MMM/dd)时,我必须明确标记整个项目中的每个注释字段,如下例所示:

@MyField(dateFormat = "yyyy/MMM/dd")
private String myDiffDate;

到目前为止我已经尝试过:

  1. 无法扩展/实现注解

  2. 定义了一个常量字符串作为默认值,但除非该字符串被标记为“final”,否则它不会编译。

    String dateFormat() 默认 BooClass.MyConstant;


在这种情况下我有什么选择?

【问题讨论】:

    标签: java annotations


    【解决方案1】:

    我尝试使用数组来操纵注释的默认值,假设它与通过引用存储值相同。但它不起作用,并且似乎在数组的情况下它返回一个克隆版本。试试下面的代码...

    在运行时,您需要提供“test”作为参数 -

        import java.lang.annotation.ElementType;
        import java.lang.annotation.Retention;
        import java.lang.annotation.RetentionPolicy;
        import java.lang.annotation.Target;
    
        public class ManipulateAnnotationDefaultValue {
    
        public static void main(String[] args) throws NoSuchFieldException, SecurityException {
    
            String client = args.length > 0 ? args[0] : "default";
            MyField annotation = DefaultMyField.class.getDeclaredField("format").getAnnotation(MyField.class);
    
            String[] defaultValue = annotation.dateFormat();
            System.out.println("Hash code of MyField.dateFormat = " + defaultValue.hashCode());
            System.out.println("Value of MyField.dateFormat = " + defaultValue[0]);
    
            if (!client.equals("default")) {
                System.out.println("Changing value of MyField.dateFormat[0] to = 'dd-MM-yyyy'");
                defaultValue[0] = "dd-MM-yyyy"; // change the default value of annotation //$NON-NLS-1$
            }
    
            defaultValue = annotation.dateFormat();
            System.out.println("Hash code of MyField.dateFormat = " + defaultValue.hashCode());
            System.out.println("Value of MyField.dateFormat = " + defaultValue[0]);
        }
    }
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface MyField {
    
        String[] dateFormat() default {"dd/MM/yyyy"};
    }
    
    class DefaultMyField {
    
        @MyField
        String format;
    
    }
    

    下面是输出 -

    Hash code of MyField.dateFormat = 356573597
    Value of MyField.dateFormat = dd/MM/yyyy
    Changing value of MyField.dateFormat[0] to = 'dd-MM-yyyy'
    Hash code of MyField.dateFormat = 1735600054
    Value of MyField.dateFormat = dd/MM/yyyy
    

    【讨论】:

      猜你喜欢
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 2016-07-29
      • 2020-06-07
      相关资源
      最近更新 更多