Reputation: 743
how can I write a custom annotation that takes another annotation and the values?
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation{
Class<? extends TestAnnotationChild> annotation();
}
The second annotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotationChild{
}
And I would like to do something like
@TestAnnotation(@TestAnnotationChild={values})
How can I do something like that?
Upvotes: 3
Views: 3020
Reputation: 11050
You should just use TestAnnotationChild value();
instead of 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();
}
Now you can use the Annotations as you wanted:
@TestAnnotation(@TestAnnotationChild({"TEST"}))
Upvotes: 2
Reputation: 21172
This is how it is done.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
TestAnnotationChild child();
// Or for an array
TestAnnotationChild[] children();
}
Usage
@TestAnnotation(
@TestAnnotationChild(
value = "42",
anotherValue = 42
)
)
However this part of your statement
and the values
does make me think you want to do something non-ordinary.
Could you clarify?
Upvotes: 4
Reputation: 1216
you can just have a property of type TestAnnotationChild
in your TestAnnotation
, just like it was a string, or whatever else
Upvotes: 0