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 (
@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.
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?
No, you can't use null
for an annotation attribute value. However you can use an array type and provide an empty array.
public @interface Foo {
Config[] value();
}
...
@Foo(value = {})
or
public @interface Foo {
Config[] value() default {};
}
...
@Foo
try that:
Config value() default @Config();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With