Java自定义注解需要另一个注解

3

我该如何编写一个自定义的注解,以便接收另一个注解和值?

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{
  Class<? extends TestAnnotationChild> annotation();
}

第二个注释
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotationChild{

}

我希望能够做类似以下的事情:

@TestAnnotation(@TestAnnotationChild={values})

我该如何做类似于这样的事情?

3个回答

4

这就是它的实现方式。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
   TestAnnotationChild child();

   // Or for an array
   TestAnnotationChild[] children();
}

使用方法

@TestAnnotation(
        @TestAnnotationChild(
               value = "42",
               anotherValue = 42
        )
)

然而,你声明中的这部分内容

以及价值观

让我想到你想要做一些非寻常的事情
你能否澄清一下?


2
你应该使用TestAnnotationChild value();而不是Class<? extends TestAnnotationChild> annotation();。最初的回答。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{
  TestAnnotationChild value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotationChild {
    // String or whatever Object you want
    String[] value();
}

现在您可以按照您的意愿使用注释:
@TestAnnotation(@TestAnnotationChild({"TEST"}))

0

你可以在你的 TestAnnotation 中,就像一个字符串或其他任何类型一样,拥有一个类型为 TestAnnotationChild 的属性


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接