简体   繁体   English

Java中的注释元素可以是不同注释的数组吗?

[英]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. 我正在尝试用Java创建自定义注释,问题是是否可以使用“注释数组”类型的元素创建自定义注释,并且此数组中的每个元素都将来自不同的类型。

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: Java语言规范的第9.6.1节指出,注释元素/成员可以是以下类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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