sockeqwe
sockeqwe

Reputation: 15929

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?

Upvotes: 29

Views: 34450

Answers (3)

mipo256
mipo256

Reputation: 3214

The @Sotirios Delimanolis answer is correct, but I would like to explain on why this restriction even exists.

In Java, annotation attribute values cannot be null because the JLS defines that annotation attributes must have a constant value known at compile-time. Therefore, an annotation attribute can possibly be:

  1. A constant expression that is known at compile-time (like 1, "Hello", Month.JULY, etc.)
  2. An element value pair (afaik it is like other annotations @Config)
  3. An array initializer (like {1, 2, 3})

As you see, null is not considered as a value known at compile-time. Therefore you have this restriction. So it's not that null is somehow specifically excluded as an annotation value by language developers, it's just not considered to be known at compile time :)

Upvotes: 2

jepac daemon
jepac daemon

Reputation: 69

try that:

Config value() default @Config();

Upvotes: 6

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280141

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

Upvotes: 37

Related Questions