Eigene Annotation und Reflection

danielm

Erfahrenes Mitglied
Aloha,

Ich habe mir meine eigene Annotation @Id erstellt die spezielle Felder von Klassen kennzeichnen sollen. Das ganze wird dann später per Reflection analysiert. Allerdings klappt es nicht.

PHP:
public @interface Id {}

PHP:
public class MyBean {
  @Id
  private Integer id;
}

PHP:
for(Field f : obj.getClass().getDeclaredFields()) {
  Id idA = f.getAnnotation(Id.class);
  if(idA == null)
    System.out.println(f.getName() + " has no annotation");
  else
    System.out.println(f.getName() + " has ID annotation");
}

Als Ausgabe bekomme ich immer "has no annotation". Wenn ich das Ganze, zum Testen, mit der @Deprecated Annotation mache funktioniert es.

Hat zufällig jemand Erfahrungen damit? ;)

Gruß Daniel
 
Damit das geht, muss die Annotation zur Laufzeit zur Verfügung stehen, daher:
Java:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Id {}
So klappts. Hab außerdem dafür gesorgt, dass die Annotation nur bei Variablen geht, da es bei Methoden, Klassen, Konstruktoren, usw. nicht so wirklich Sinn macht.
 
Zuletzt bearbeitet:
Zurück