2013-05-08 106 views
2

我在java中定製了一個帶有一個值的字符串(String []);自定義註釋錯誤

@Retention(value = RetentionPolicy.RUNTIME) 
public @interface MyAnnotation{ 
    String[] value(); 
} 

但是,我想要的值,當我用MyAnnotation-是這樣的:aClassName.anAttribute

  • aClassName是在我的應用程序類的名稱
  • anAttribute是一個它的屬性是一個字符串:

    public static String anAttribute1="aStringxxx";

但是我得到一個錯誤:The value for annotation attribute MyAnnotation.value must be a constant expression 有沒有人有想法嗎?

+2

使屬性最終。 – maba 2013-05-08 14:27:17

+0

您的意思是讓值爲'String []'而不是'String'? – 2013-05-08 14:37:52

+0

謝謝^^我在屬性中添加了最終的內容,並且錯誤消失了! – M810 2013-05-08 15:01:00

回答

2

如果您的屬性final它會工作得很好。

public class SomeClass { 
    public static final String myAttribute = "abc"; 
} 

@Retention(value = RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
    String[] value(); 
} 

public class SomeOtherClass { 
    @MyAnnotation({SomeClass.myAttribute}) 
    private int someInt; 
} 
0

我不確定是否正確理解您的問題,但AFAIK不能使用在使用註釋的同一類中定義的常量。

可能的解決方案:移動常數一個輔助類

1

的解決方案是標記anAttribute1作爲static final使之成爲常量表達式。

class MyAttributeConstants { 
    public static final anAttribute1 = "someString"; 
}