How to get annotations of a member variable?

前端 未结 8 2089
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 00:29

I want to know a class\'s some member variable\'s annotations , I use BeanInfo beanInfo = Introspector.getBeanInfo(User.class) to introspect a class , and use <

相关标签:
8条回答
  • 2020-11-29 00:53

    My way

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    
    public class ReadAnnotation {
        private static final Logger LOGGER = LoggerFactory.getLogger(ReadAnnotation.class);
    
        public static boolean hasIgnoreAnnotation(String fieldName, Class entity) throws NoSuchFieldException {
            return entity.getDeclaredField(fieldName).isAnnotationPresent(IgnoreAnnotation.class);
        }
    
        public static boolean isSkip(PropertyDescriptor propertyDescriptor, Class entity) {
            boolean isIgnoreField;
            try {
                isIgnoreField = hasIgnoreAnnotation(propertyDescriptor.getName(), entity);
            } catch (NoSuchFieldException e) {
                LOGGER.error("Can not check IgnoreAnnotation", e);
                isIgnoreField = true;
            }
            return isIgnoreField;
        }
    
        public void testIsSkip() throws Exception {
            Class<TestClass> entity = TestClass.class;
            BeanInfo beanInfo = Introspector.getBeanInfo(entity);
    
            for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
                System.out.printf("Field %s, has annotation %b", propertyDescriptor.getName(),  isSkip(propertyDescriptor, entity));
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 00:55

    Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME):

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface MyAnnotation{
        int id();
    }
    
    0 讨论(0)
提交回复
热议问题