如何在@括号(“Luke”)之类的java注释中使用括号内没有属性?
如何在括号内没有属性名称的自定义java注释?
我不想要这个: @annotation_name(att=valor)
。 我只想在Servlets中,即:
@WebServlet("/main")
使用名为value
的属性定义注释,然后可以省略属性名称 :
@interface CustomAnnotation { String value(); }
这可以这样使用:
@CustomAnnotation("/main") // ...
您指定名为value的属性:
public @interface MyAnnotation { String value(); }
如果它们具有默认值,则不必是唯一的属性:
public @interface MyAnnotation { String value(); int myInteger() default 0; }
但是,如果要显式为值以外的属性赋值,则必须显式赋值。 也就是说:
@MyAnnotation("foo") @MyAnnotation(value = "foo", myInteger = 1)
作品
但
@MyAnnotatino("foo", myInteger = 1)
才不是
引用注释官方文档 :
如果只有一个名为“
value
”的元素,则可以省略该名称,如:
@SuppressWarnings("unchecked") void myMethod() { }
这是注释的定义方式:
public @interface SuppressWarnings { String[] value(); }
正如您所看到的,文档并不完全正确,也允许使用其他属性(“ 只需一个元素 ”),请参阅WebServlet
– 但是对一个命名value
的处理方式不同。