Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom annotations takes another annotation

Tags:

java

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?

like image 498
Reddi Avatar asked Jun 10 '26 12:06

Reddi


1 Answers

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?

like image 191
LppEdd Avatar answered Jun 12 '26 02:06

LppEdd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!