2

I have two annotations. The first is used from the second:

@Target({ })
@Retention(RUNTIME)
public @interface A {

   String value() default "";

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface B {

    A a() default ???;

}

The logic that @B can be used without any attributes, but, of course, it doesn't mean (by Annotation specification) that it will have nulls for its attributes.

From other side @A.value() == "" is also OK for my logic. That means:

A a() default @A;

Isn't for me.

So, I need a case, when I can determine that @B.a() is something like 'NO_VALUE' and it should be protected from end-user.

static final A NO_A = new A() {};

A a() default NO_A;

Doesn't help: it isn't compiled.

As a workaround I use an array:

A[] a() default {};

And check in the annotation processor the size of a attribute.

Are there some other options to mark a() with something default to make it 'NULL'-like and get rid of an array style ?

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118

1 Answers1

1

There doesn't seem to be any clean way to create default null values for annotation fields. Here's some information why it was design this way and workarounds when using class types: Error setting a default null value for an annotation's field

I think using arrays like you proposed is a good way of handling this. Just document that it's an array for technical reasons and throw an error when used with more than one element.

The only other solution that comes to my mind is using magic strings as the value of the default A. Depending on the use case I would either choose some long random string that is unlikely to be used any users or document whatever other special value is used.

public @interface B {
    final String DEFAULT = "_a_default_value";
    A a() default @A(DEFAULT);
}
Community
  • 1
  • 1
kapex
  • 28,903
  • 6
  • 107
  • 121
  • OK. Thanks. I think I go ahead with `array`, because you can use it as single value attribute. From other side my annotation doesn't have `value` attrbiute, but has a lot of others non-String attrbiutes with their default values. And I can't introduce new 'fake' `value` attrbiute, since my annotation is a public API of Open Source Framework. – Artem Bilan Apr 03 '14 at 12:34