如何编写带有另一个注释和值的自定义注释?
@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})
我怎么能这样做?
这就是它的完成方式。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
TestAnnotationChild child();
// Or for an array
TestAnnotationChild[] children();
}
用法
@TestAnnotation(
@TestAnnotationChild(
value = "42",
anotherValue = 42
)
)
不过这部分是你的陈述
和价值观
确实让我觉得你想做一些非平凡的事情。 你能澄清一下吗?
你应该使用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"}))
你可以在你的TestAnnotationChild
中拥有TestAnnotation
类型的属性,就像它是一个字符串,或者其他任何东西