如何在@括号("Luke")之类的java注释中使用括号内没有属性?

Luc*_*ssi 38 java attributes annotations default parentheses

如何在括号内没有属性名称的自定义java注释?

我不希望这样:@annotation_name(att=valor).我只想在Servlets中,即:

@WebServlet("/main")
Run Code Online (Sandbox Code Playgroud)

pb2*_*b2q 44

使用名为的属性定义注释value,然后可以省略属性名称:

@interface CustomAnnotation
{
    String value();
}
Run Code Online (Sandbox Code Playgroud)

这可以这样使用:

@CustomAnnotation("/main")
// ...
Run Code Online (Sandbox Code Playgroud)


Dou*_*rop 26

您指定名为value的属性:

public @interface MyAnnotation {

    String value();

}
Run Code Online (Sandbox Code Playgroud)

如果它们具有默认值,则不必是唯一的属性:

public @interface MyAnnotation {

    String value();
    int myInteger() default 0;

}
Run Code Online (Sandbox Code Playgroud)

但是,如果要显式为值以外的属性赋值,则必须显式赋值.也就是说:

@MyAnnotation("foo")
@MyAnnotation(value = "foo", myInteger = 1)
Run Code Online (Sandbox Code Playgroud)

作品

@MyAnnotatino("foo", myInteger = 1)
Run Code Online (Sandbox Code Playgroud)

才不是


Tom*_*icz 11

引用注释官方文档:

如果只有一个名为" value"的元素,则可以省略该名称,如:

@SuppressWarnings("unchecked")
void myMethod() { }
Run Code Online (Sandbox Code Playgroud)

这是注释的定义方式:

public @interface SuppressWarnings {
  String[] value();
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,文档不完全正确,也允许其他属性(" 只是一个元素 "),请参阅WebServlet- 但命名的文件value将被区别对待.