首页 > 解决方案 > Java 自定义注解采用另一个注解

问题描述

如何编写一个带有另一个注释和值的自定义注释?

@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

解决方案


这就是它的完成方式。

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

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

用法

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

但是,您声明的这一部分

和价值观

确实让我觉得你想做一些不寻常的事情
你能澄清一下吗?


推荐阅读