[英]Is it possible to make a Java annotation's value mandatory?
Java allows the definition of values in annotations, for example: Java 允许在注解中定义值,例如:
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.虽然可以为
MyValue
注释设置默认值,但我想知道是否可以强制设置。 What I mean is forcing the user to provide a value for MyValue
when annotating a class or field.我的意思是强制用户在注释 class 或字段时为
MyValue
提供一个值。
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:对于您的示例,使用您的注释而不使用
MyValue
属性会生成此编译器错误:
annotation MyAnnotation is missing MyValue
注释 MyAnnotation 缺少 MyValue
Given给定
public @interface MyAnnotation {
int MyValue();
}
a class一个 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.其中 Status 是一个枚举。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.