2016-02-02 69 views
1

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

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. 定义的常量字符串作为默认值,但它不会编译除非字符串被标记为“最终”。

    String dateFormat()默认BooClass.MyConstant;


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

回答

0

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

在运行,你需要提供 “测试” 作为参数 -

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