2014-01-28 99 views
0

我在自定義註釋下面寫了。創建自定義註釋並在java中使用它?

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 

    String value(); 

} 

我正在使用下面的註釋。

@MyAnnotation("someValue") 
public void someMethod(){ 


} 

上面的代碼工作正常,沒有任何問題。 但是在註釋類中,值()方法名稱我必須重新排列。我可以做如下嗎?

@Target(ElementType.METHOD) 
    @Retention(RetentionPolicy.RUNTIME) 
    public @interface MyAnnotation { 

     String name(); 

    } 

我試過但eclipse給出了編譯錯誤。

- The attribute value is undefined for the annotation type 
    MyAnnotation 
    - The annotation @MyAnnotation must define the attribute 
    name 

任何原因?

+0

由於我不是得到任何錯誤。所以請張貼您的錯誤呢? – Prateek

+0

Prateek,我編輯了我的問題... – user755806

+0

看看我的回答 – Prateek

回答

3

使用方法如下:

@MyAnnotation(name="someValue") 
public void someMethod(){ 


} 

因爲默認情況下注釋具有價值的方法,所以如果你指定這樣

@MyAnnotation("someValue") 
    public void someMethod(){ 


    } 

它會默認把它當作value="someValue"

+0

感謝Prateek ...它幫助.. – user755806

+0

我的榮幸。我將盡力爲您找到一些資源,併爲您提供鏈接。 – Prateek

+0

非常感謝Prateek .... – user755806