简体   繁体   中英

Elements of annotation in Java can be array of different annotations?

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?

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM