简体   繁体   中英

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?

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

Given

public @interface MyAnnotation {
    int MyValue();
}

a class

@MyAnnotation
public class MyClass {

}

will be a compile error without a value.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM