繁体   English   中英

创建自定义注释并在Java中使用它?

[英]creating custom annotation and using it in java?

我已经在“自定义注释”下面写了。

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

    String value();

}

并使用以下注释。

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


}

上面的代码工作正常,没有任何问题。 但是在注释类中,我必须重命名value()方法名称。 我可以做以下事情吗?

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

        String name();

    }

我试着做,但日食给编译错误。

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

任何原因?

像这样使用它:

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


}

因为默认情况下注解具有值方法,所以如果您这样指定

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


    }

默认情况下,它将value="someValue"value="someValue"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM