2013-02-01 34 views
3
public @interface MyAnnotation{ 

    public String someProperty(); 

    //How should I achieve this? 
    public String someOtherProperty() default someProperty(); 


} 

我在註釋中有兩個屬性,當沒有指定一個屬性時,我想使用另一個作爲默認值。有沒有辦法做到這一點?使用一個註釋方法作爲其他默認值

還是我要做以下檢查

if(myAnnotation.someOtherProperty() == null){ 
    //Use the value of someProperty 
} 
+1

@XaviLópez它不重複,因爲這個問題詢問如何使用其中一個屬性作爲默認值。您提供的鏈接討論瞭如何使用默認值。 –

+0

來到這裏希望瞭解_methods_如何使用註釋。所提供的鏈接不包含該信息。 –

回答

4

您當前的情況是根本不可能的 - 一個註釋屬性的默認值必須是靜態解析。現在,您正試圖將默認值定義爲一個屬性,該屬性在實際使用註釋之前不會被設置(也就是動態地)。

你可以做的是定義你的註解這樣:

public @interface MyAnnotation{ 

    public String someProperty(); 

    public String someOtherProperty() default ""; 
} 

然後在你的批註處理器,使用的someProperty的價值someOtherProperty,如果someOtherProperty是空白。

相關問題