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

JavaAttributesAnnotationsDefaultParentheses

Java Problem Overview


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")

Java Solutions


Solution 1 - Java

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")
// ...

Solution 2 - Java

You specify an attribute named value:

public @interface MyAnnotation {

    String value();

}

This doesn't have to be the only attribute if they have default values:

public @interface MyAnnotation {

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

}

But if you want to explicitly assign a value to the attribute other than value, you then must explicitly assign value. That is to say:

@MyAnnotation("foo")
@MyAnnotation(value = "foo", myInteger = 1)

works

but

@MyAnnotatino("foo", myInteger = 1)

does not

Solution 3 - Java

Quoting Annotations official documentation:

> If there is just one element named value, then the name may be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() { }

This is how this annotation is defined:

public @interface SuppressWarnings {
  String[] value();
}

As you can see the documentation isn't entirely right, other attributes are also allowed ("just one element"), see WebServlet - but the one named value is treated differently.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucas BatistussiView Question on Stackoverflow
Solution 1 - Javapb2qView Answer on Stackoverflow
Solution 2 - JavaDoug MoscropView Answer on Stackoverflow
Solution 3 - JavaTomasz NurkiewiczView Answer on Stackoverflow