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");
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)
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());
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With