Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation default "null" value

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?

like image 282
sockeqwe Avatar asked Jul 10 '14 16:07

sockeqwe


2 Answers

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
like image 157
Sotirios Delimanolis Avatar answered Oct 04 '22 11:10

Sotirios Delimanolis


try that:

Config value() default @Config();
like image 40
jepac daemon Avatar answered Oct 04 '22 12:10

jepac daemon