javaattributesannotationsdefaultparentheses

How can I do Java annotation like @name("Luke") with no attribute inside parenthesis?


How I can do custom Java annotation with no attribute name inside parentheses?

I don't want this: @annotation_name(att=valor). I just want like in Servlets, i.e:

@WebServlet("/main")

Solution

  • Define the annotation with an attribute named value, then the attribute name can be omitted:

    @interface CustomAnnotation
    {
        String value();
    }
    

    This can be used like so:

    @CustomAnnotation("/main")
    // ...
    

    The special attribute name value is described in chapter "9.6.1. Annotation Interface Elements" of Java Language Specification:

    By convention, the name of the sole element in a single-element annotation interface is value. Linguistic support for this convention is provided by single-element annotations (§9.7.3).