0

I have a custom annotation:

@Target({ElementType.METHOD}) // NOTE: ElementType is METHOD
public @interface MyAnnotation {
}

I have a generic class that takes a generic bounded type:

class MyWork<T extends Annotation> {
    T theAnnotation;

    public ElementType checkAnnotationElementType() {
        // how to get the target elementType of theAnnoation?
    }

}

What I want to achieve is to get the target element type of the T theAnnotation. For example the end result I want to achieve is:

 MyWork<MyAnnotation> foo = new MyWork();
 ElementType type = foo.checkAnnotationElementType(); // returns ElementType.METHOD

How can I get the element type from the generic type variable theAnnotation ?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354

1 Answers1

1

You could do something like that. Get annotation from annotation. Make note that annotation can have more than one target type.

Note - you have to instantiate your field somehow - constructor seems like good way, generic can be ommited.

ElementType[] target = new MyWork<>(MyAnnotation.class).checkAnnotationElementType();
class MyWork<T extends Annotation> {

    private final Class<T> annotationClass;

    public MyWork(Class<T> annotationClass) {
        this.annotationClass = annotationClass;
    }

    public ElementType[] checkAnnotationElementType() {
        return annotationClass.getAnnotation(Target.class).value();
    }
}
Worthless
  • 531
  • 3
  • 7