Java 注释默认“空”值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24681223/
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
Annotation default "null" value
提问by sockeqwe
Is it possible to specify a annotation with a null as default?
是否可以将注释指定为默认值?
What I want to achieve is something like optional annotation attributes.
我想要实现的是诸如可选注释属性之类的东西。
For example
例如
public @interface Foo {
Config value();
}
public @interface Config {
boolean ignoreUnknown() default false;
int steps() default 2;
}
I would like to use @Foo (without specifying the value, so it should be some kind of optional) and I would also like to be able to write something like this:
我想使用@Foo(不指定值,所以它应该是某种可选的),我也希望能够写出这样的东西:
@Foo (
@Config(
ignoreUnknown = true,
steps = 10
)
)
Is it possible to do something like this with annotations?
是否可以使用注释来做这样的事情?
I don't want to do something like this
我不想做这样的事情
public @interface Foo {
boolean ignoreUnknown() default false;
int steps() default 2;
}
because I want to be able to distinguish if a property has been set or not (and not if it has the default value or not).
因为我希望能够区分一个属性是否已设置(而不是它是否具有默认值)。
It's a little bit complicated to describe, but I'm working on a little Annotation Processor which generates Java code. However at runtime I would like to setup a default config that should be used for all @Foo, excepted those who have set own configuration with @Config.
描述起来有点复杂,但我正在研究一个生成 Java 代码的小注解处理器。但是在运行时,我想设置一个默认配置,该配置应该用于所有@Foo,除了那些使用@Config 设置自己的配置的配置。
so what I want is something like this:
所以我想要的是这样的:
public @interface Foo {
Config value() default null;
}
But as far as I know its not possible, right? Does anybody knows a workaround for such an optional attribute?
但据我所知这是不可能的,对吧?有人知道这种可选属性的解决方法吗?
采纳答案by Sotirios Delimanolis
No, you can't use null
for an annotation attribute value. However you can use an array type and provide an empty array.
不,您不能null
用于注释属性值。但是,您可以使用数组类型并提供一个空数组。
public @interface Foo {
Config[] value();
}
...
@Foo(value = {})
or
或者
public @interface Foo {
Config[] value() default {};
}
...
@Foo
回答by jepac daemon
try that:
试试看:
Config value() default @Config();