25

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?

Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
sockeqwe
  • 15,574
  • 24
  • 88
  • 144
  • 1
    Possible duplicate of [Error setting a default null value for an annotation's field](http://stackoverflow.com/questions/1178104/error-setting-a-default-null-value-for-an-annotations-field) – fracz Jan 05 '16 at 08:10

2 Answers2

34

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
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
6

try that:

Config value() default @Config();
wolmi
  • 1,659
  • 12
  • 25
jepac daemon
  • 69
  • 1
  • 1