我在自定义注释下面写了。
@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();
}
我尝试这样做,但 Eclipse 给出了编译错误。
- The attribute value is undefined for the annotation type
MyAnnotation
- The annotation @MyAnnotation must define the attribute
name
有什么理由吗?
最佳答案
像这样使用它:
@MyAnnotation(name="someValue")
public void someMethod(){
}
因为默认情况下注释有 value 方法,所以如果您这样指定
@MyAnnotation("someValue")
public void someMethod(){
}
它默认将其视为value="someValue"
关于java - 创建自定义注释并在java中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399318/