Is it possible to make a Java annotation's value mandatory?

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?

Upvotes: 65

Views: 42524

Answers (3)

Clint
Clint

Reputation: 9058

Given

public @interface MyAnnotation {
    int MyValue();
}

a class

@MyAnnotation
public class MyClass {

}

will be a compile error without a value.

Upvotes: 12

Yargis
Yargis

Reputation: 17

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.

Upvotes: 0

Stefan Schubert-Peters
Stefan Schubert-Peters

Reputation: 5459

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

Upvotes: 110

Related Questions