62

Java allows the definition of values in annotations, for example:

public @interface MyAnnotation {
    int MyValue();
}

Although it is possible to set a default value for the MyValue annotation, I was wondering whether it is possible to make it mandatory. What I mean is forcing the user to provide a value for MyValue when annotating a class or field.

I went through the documentation but could not find anything. Does anyone have a solution to this issue or is it just impossible to make an annotation's value mandatory?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • It should be noted that the return type of `MyValue` is only permitted to be a "primitive type, String, Class, annotation, enumeration...or 1-dimensional arrays thereof." – Vessel Apr 02 '23 at 02:18

3 Answers3

107

If you do not specify a default value, it is mandatory. For your example using your annotation without using the MyValue attribute generates this compiler error:

annotation MyAnnotation is missing MyValue

Stefan Schubert-Peters
  • 5,419
  • 2
  • 20
  • 21
11

Given

public @interface MyAnnotation {
    int MyValue();
}

a class

@MyAnnotation
public class MyClass {

}

will be a compile error without a value.

oligofren
  • 20,744
  • 16
  • 93
  • 180
Clint
  • 8,988
  • 1
  • 26
  • 40
0

I haven't tried this but if you are wanting to force the values to a specific value perhaps making the type an enum.

public @interface MyAnnotation {
    Status status();
}

Where Status is an enum.

Yargis
  • 17
  • 1