TYPE_USE Annotation an implementiertem Interface auslesen

Gegeben folgender seltsame Code:

@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

public interface MyInterface{}

class MyClass implements @MyAnnotation MyInterface {
}

Kann ich mit Reflection-Bordmitteln herausfinden, ob diese Annotation gesetzt ist, oder brauche ich einen Annotation-Prozessor?

Das geht so:

System.out.println( "Instanz der annotation " + MyClass.getAnnotation(MyAnnotation.class));

Ich sehe gerade das sitzt am interface. Das ist aber extrem unüblich. Ich schaue eben nach.

Also ich bin der Meinung, dass du durch die annotation m Interface nichts gewonnen hast. Es würde so oder so die gesamte Klasse betreffen.

Schreibe das Interface an die Klasse und gebe das konkrete Interface dort an, auf das sich die annotation bezieht.

Ja, das wäre eine Lösung, aber direkt am Interface wäre es deutlich lesbarer.

Es ist wirklich ärgerlich, dass Reflection so beschränkt ist.

Ich hab’ keine Ahnung worum’s hier geht, aber…

Class c = MyClass.class;
AnnotatedType[] annotatedInterfaces = c.getAnnotatedInterfaces();
boolean yeahItIsThere = annotatedInterfaces[0].isAnnotationPresent(MyAnnotation.class); 
MyAnnotation[] itIsThat = annotatedInterfaces[0].getAnnotationsByType(MyAnnotation.class);
System.out.println(yeahItIsThere+" : "+Arrays.toString(itIsThat));

das gibt true : [@bytewelt.anno.MyAnnotation()] aus. Ist’s das?

2 „Gefällt mir“

Danke, das habe ich gesucht