3

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?

3 Answers 3

4

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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"}))

Comments

0

you can just have a property of type TestAnnotationChild in your TestAnnotation, just like it was a string, or whatever else

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.