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

问题描述 投票:3回答: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})

我怎么能这样做?

java
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();
}

现在您可以根据需要使用Annotations:

@TestAnnotation(@TestAnnotationChild({"TEST"}))

0
投票

你可以在你的TestAnnotationChild中拥有TestAnnotation类型的属性,就像它是一个字符串,或者其他任何东西

© www.soinside.com 2019 - 2024. All rights reserved.