Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotations are not found, during loop

I am running this code into a junit test. However, the annotations are not found and nothing is outputted. What could cause this.

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Datafield {
}

public class EntityTest 
{
    @Datafield
    StandardFieldText username;

    @Test
    public void TestEntityAnnotation() throws NoSuchFieldException, SecurityException
    {
        EntityTest et = new EntityTest();

        Annotation[] annos = et.getClass().getAnnotations();

        for(Annotation a : annos)
            System.out.println(a);


    }
}
like image 509
Anon21 Avatar asked Dec 02 '25 03:12

Anon21


2 Answers

You're requesting the annotations of EntityTest class which indeed has no annotations.

In order to get the annotation above the field you should try:

Field f = ep.getDeclaredField("username");
Annotation[] annos = f.getDeclaredAnnotations();
like image 149
Avi Avatar answered Dec 04 '25 18:12

Avi


You requested the annotations of the class itself. You should loop through methods, fields, etc. to retrieve the annotations of these elements: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

For instance:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Datafield {
}

public class EntityTest 
{
    @Datafield
    StandardFieldText username;

    @Test
    public void TestEntityAnnotation() throws NoSuchFieldException, SecurityException
    {
        EntityTest et = new EntityTest();
        for(Method m : et.getClass().getDeclaredMethods()) {
            Annotation[] annos = m.getDeclaredAnnotations();
            for(Annotation a : annos)
                System.out.println(a);
        }

    }
}
like image 43
Willem Van Onsem Avatar answered Dec 04 '25 17:12

Willem Van Onsem