10

I want to write an annotation that hast a EnumArray Field. Default value should be all values of the Enum. This code works but I don't want to specify every enum manually.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CommonScope
{
    ECountry[] countries() default {ECountry.AT, ECountry.DE};

}

I want to do something like this:

ECountry[] countries() default ECountry.values();

Can someone tell me how to achieve this?

Thank you

5
  • you can use EnumSet.allOf(ECountry.class) Commented Mar 4, 2015 at 9:29
  • @KennethClark - How - I can't seem to make that work. n'or does EnumSet.allOf(A.class).toArray(). Commented Mar 4, 2015 at 9:51
  • Hm does not work. I get the same error when I Use values() ... Eclipse tells me "The value for annotation attribute CommonScope.countries must be an enum constant expression" Commented Mar 4, 2015 at 9:52
  • you tried public static ECountry[] COUNTRY = (EStatus[]) EnumSet.allOf(ECountry.class).toArray(); Commented Mar 4, 2015 at 10:37
  • This will add all the values , not sure is that's what you expected , if you want specific values .. Like just two countries but the enum contains 10 you will have to add a little more logic. Commented Mar 4, 2015 at 10:46

1 Answer 1

11

This is not possible, annotation declaration is very limited. You can not call any methods or use properties, you can only use compile time constant expressions, that are known at compile time by the compiler.

As a workaround, you could add a special enum value like Countries.ALL_COUNTRIES if that makes sense for your application.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.