java自定义注释:使属性可选

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1357945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:07:07  来源:igfitidea点击:

java custom annotation: make an attribute optional

javaannotationsmetaprogramming

提问by flybywire

I defined my own custom annotation

我定义了自己的自定义注释

@Target(value={ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation  {
    Class<?> myType();
}

how, if at all, can I make the attribute optional

如果有的话,我如何使属性可选

采纳答案by Dan Dyer

You can provide a default valuefor the attribute:

您可以属性提供默认值

@Target(value={ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation  {
    Class<?> myType() default Object.class;
}

回答by flybywire

Found it. It can't be optional, but a default can be declared like this:

找到了。它不能是可选的,但可以像这样声明默认值:

@Target(value={ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation  {
    Class<?> myType() default String.class;
}

If no default can make sense as "empty" value then that is a problem.

如果没有默认值可以作为“空”值有意义,那么这是一个问题。

回答by Dhiral Pandya

For Optional attribute you need to provide default value for that attribute you can provide default value using "default" keyword.

对于 Optional 属性,您需要为该属性提供默认值,您可以使用“default”关键字提供默认值。

Note : For only one attribute you can use attribute name as value. If you use your attribute name as valueyou can directly pass value like this @MyCustomAnnotation(true) instead of @MyCustomAnnotation(myType = true).

注意:对于只有一个属性,您可以使用属性名称作为。如果您使用您的属性名称作为值,您可以直接传递这样的值 @MyCustomAnnotation(true) 而不是 @MyCustomAnnotation(myType = true)。

See this example for more details

有关更多详细信息,请参阅此示例