简体   繁体   中英

Reflection can not find annotation

I can not get annotations of beans, i'm working with spring framework:

Runnable test class:

public class Main {

    public static void main(String[] args) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(Test.class,"foo");
        Method m=pd.getReadMethod();
        System.out.println(m.isAnnotationPresent(Annot.class));
    }

}

Bean class;

public class Test {

    private String foo;

        @Annot
        public String getFoo() {
            return foo;
        }

        public void setFoo(String foo) {
            this.foo = foo;
        }

    }

Annotation class:

public @interface Annot {

}

The main class get "false" as output... why?

Your annotation is missing a runtime retention policy.

Do the following:

@Retention(RetentionPolicy.RUNTIME)
public @interface Annot {

}

Check out this SO question which explains the default policy and what it does. To sum the information in that answer, the default retention policy is CLASS , which means that the annotation is in the bytecode, but does not have to be retained when the class is loaded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM