开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜