Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isAnnotationPresent(Id.class) is not working for the class file

I have a class file test.class. In that file there is annotations as @Id and @Entity. But when i check for the annotation with the method field.isAnnotationPresent(Id.class), it returns false. I am getting all the fields in field variable.

Can any body tell me what mistake i did.

update:am using the following code to get the class

File file=new File("D:/test/");
URL url=file.toURL();
URL[] urls=new URL[]{url};
ClassLoader loader=new URLClassLoader(urls);
Class cls=loader.loadClass("com.net.test.Test");
like image 321
Kamalam Avatar asked Mar 23 '12 08:03

Kamalam


3 Answers

Have you annotated your annotation with a retention policy? If no retention policy is set the default retention policy behaviour is that the annotation is read by the compiler and also retained in the generated .class files but won't be accesible during runtime. If you need the annotation in runtime you need to annotate your annotations with:

@Retention(RetentionPolicy.RUNTIME)  
like image 165
Fredrik LS Avatar answered Sep 30 '22 06:09

Fredrik LS


Your test's classloader may have a different Id than loader's.

A quick way to check:

...
Class idType = loader.loadClass("my.package.Id");
...
field.isAnnotationPresent(idType);

If that works, then you have a classloader problem -- more specifically, your loader does not use your test case's loader. To fix, use a different constructor:

ClassLoader loader = new URLClassLoader(urls, this.getClass().getClassLoader());
like image 31
Dilum Ranatunga Avatar answered Sep 30 '22 07:09

Dilum Ranatunga


It works in general. Here's a working example:

import java.lang.reflect.Field;

public class AnnotationTest {

    @Deprecated
    public static int value = 1;

    public static void main(String[] args) throws Exception {
        Field field = AnnotationTest.class.getField("value");
        System.out.println(field.isAnnotationPresent(Deprecated.class));
    }
}

Double-check your classnames and imports. Maybe you accidentally check for a wrong Id.class (nameclash).

like image 35
Andreas Dolk Avatar answered Sep 30 '22 06:09

Andreas Dolk