2014-01-28 47 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