简体   繁体   English

多个注释

[英]Multiple annotations

Since it is not possible to have duplicated annotations on the same target, I'm working on a workaround for it. 由于不可能在同一目标上有重复的注释,我正在为它做一个解决方法。 What I need is something likely to : 我需要的是可能的东西:

@Parent(sex="F", name="Alice")
@Parent(sex="M", name="Bob")
@Sibling(sex="M", name="Charlie")
@Sibling(sex="M", name="Dan")
@Sibling(sex="F", name="Eve")

I've though of adding another annotation @Relatives to contain them all, declaring the value member as an array of Relative annotations. 我想添加另一个注释@Relatives来包含它们,将值成员声明为相对注释数组。

@Relatives({
    @Parent(sex="F", name="Alice")
    @Parent(sex="M", name="Bob")
    @Sibling(sex="M", name="Charlie")
    @Sibling(sex="M", name="Dan")
    @Sibling(sex="F", name="Eve")
})

However I can't define an array like that since @Parent and @Sibling @interfaces can't extend any @Relative superclass. 但是我无法定义这样的数组,因为@Parent和@Sibling @interfaces不能扩展任何@Relative超类。

Is there any other way to do it apart from defining two different arrays Sibling[] siblings and Parent[] parents ? 除了定义两个不同的数组兄弟姐妹[]兄弟姐妹和父[]父母之外,还有其他办法吗? But that would create something like 但这会产生类似的东西

@Relatives(
    parents={
        @Parent(sex="F", name="Alice"),
        @Parent(sex="M", name="Bob")
    }
    siblings={
        @Sibling(sex="M", name="Charlie")
        @Sibling(sex="M", name="Dan")
        @Sibling(sex="F", name="Eve")
   }
)

In 1.8 you have a half-baked way of repeatable annotations, see java.lang.annotation.Repeatable The trick is you still do need to declare your @Parents and @Siblings, but: 在1.8中你有一个半成品的可重复注释方式,请参阅java.lang.annotation.Repeatable诀窍是你仍然需要声明你的@Parents和@Siblings,但是:

  1. when using them, the containing annotations can be omitted 使用它们时,可以省略包含注释

  2. when scanning (introspecting) for them, you'll find your repeatable annotations inside their containing annotations ( @Parents and @Siblings ) in this case. 在扫描(内省)时,在这种情况下,你会在包含注释( @Parents@Siblings )中找到可重复的注释。

public @interface Parents {
      Parent[] value();
    }

    // this says: will be repeated inside a `Parents` nest
    @Repeatable(Parents.class) 
    public @interface Parent {
      String name();

      String sex() default "F";
    }

then you can 那么你也能

@Parent(sex="F", name="Alice"),
@Parent(sex="M", name="Bob")
Child firstChild;

See also "Repeating Annotations" on Oracles site 另请参阅Oracles网站上的“重复注释”

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

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