Why isAnnotationPresent (Id.class) does not work for class file

I have a class file test.class. In this file there are annotations like @Idand @Entity. But when I check the annotation using the method field.isAnnotationPresent(Id.class), it returns false. I get all the fields in a field variable.

Can anyone tell me what mistake I made.

update: I use 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");
+5
source share
4 answers

Your test class loader may have a different Idone than loader.

Quick way to check:

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

, - , loader . , :

ClassLoader loader = new URLClassLoader(urls, this.getClass().getClassLoader());
+1

? , , , .class, . , :

@Retention(RetentionPolicy.RUNTIME)  
+26

. :

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));
    }
}

. , Id.class (nameclash).

+1

If you use isAnnotationPresent () in a Spring AOP interceptor and proxyTargetclass = false add an annotation to the target interface instead of the implementation class.

0
source

All Articles