0

I'm trying to create a custom annotation in Java and the question is if it's possible to create custom annotation with element of type "Array of annotations" and each element in this array will be from different type.

For example:

@MyCustomArrayOfAnnotation({@MyCustomAnnotationType1, @MyCustomAnnotationType2})

If it's possible, how can I declare this custom annotation?

1
  • Why do you need an array? I think you are overthinking some problem and it can be done much easier. Commented Feb 11, 2018 at 10:27

1 Answer 1

2

This is not possible.

The Java Language Specification, section 9.6.1, states that annotation elements/members may be of the following types:

  • A primitive type
  • String
  • Class
  • An enum type
  • An annotation type
  • An array type whose component type is one of the preceding types.

This shows that an annotation may contain an array of annotations.

However, there is no subtyping among annotations. Therefore, an annotation can only contain a homogeneous array, not a heterogeneous one.

An example of a homogeneous array (which is allowed) is

@MyCustomArrayOfAnnotation({@MyCustomAnnotationType1("a"), @MyCustomAnnotationType1("b")})

An example of a heterogeneous array (which is not allowed) is your example:

@MyCustomArrayOfAnnotation({@MyCustomAnnotationType1, @MyCustomAnnotationType2})

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.