How to get annotations of a member variable?

前端 未结 8 2088
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    Or you could try this

    try {
        BeanInfo bi = Introspector.getBeanInfo(User.getClass());
        PropertyDescriptor[] properties = bi.getPropertyDescriptors();
        for(PropertyDescriptor property : properties) {
            //One way
            for(Annotation annotation : property.getAnnotations()){
                if(annotation instanceof Column) {
                    String string = annotation.name();
                }
            }
            //Other way
            Annotation annotation = property.getAnnotation(Column.class);
            String string = annotation.name();
        }
    }catch (IntrospectonException ie) {
        ie.printStackTrace();
    }
    

    Hope this will help.

    0 讨论(0)
  • 2020-11-29 00:38

    If you need know if a annotation specific is present. You can do so:

        Field[] fieldList = obj.getClass().getDeclaredFields();
    
            boolean isAnnotationNotNull, isAnnotationSize, isAnnotationNotEmpty;
    
            for (Field field : fieldList) {
    
                //Return the boolean value
                isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
                isAnnotationSize = field.isAnnotationPresent(Size.class);
                isAnnotationNotEmpty = field.isAnnotationPresent(NotEmpty.class);
    
            }
    

    And so on for the other annotations...

    I hope help someone.

    0 讨论(0)
  • 2020-11-29 00:40
    for(Field field : cls.getDeclaredFields()){
      Class type = field.getType();
      String name = field.getName();
      Annotation[] annotations = field.getDeclaredAnnotations();
    }
    

    See also: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html

    0 讨论(0)
  • 2020-11-29 00:42
    package be.fery.annotation;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.PrePersist;
    
    @Entity
    public class User {
        @Id
        private Long id;
    
        @Column(name = "ADDRESS_ID")
        private Address address;
    
        @PrePersist
        public void doStuff(){
    
        }
    }
    

    And a testing class:

        package be.fery.annotation;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    public class AnnotationIntrospector {
    
        public AnnotationIntrospector() {
            super();
        }
    
        public Annotation[] findClassAnnotation(Class<?> clazz) {
            return clazz.getAnnotations();
        }
    
        public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {
    
            Annotation[] annotations = null;
            try {
                Class<?>[] params = null;
                Method method = clazz.getDeclaredMethod(methodName, params);
                if (method != null) {
                    annotations = method.getAnnotations();
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            return annotations;
        }
    
        public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
            Annotation[] annotations = null;
            try {
                Field field = clazz.getDeclaredField(fieldName);
                if (field != null) {
                    annotations = field.getAnnotations();
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            return annotations;
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            AnnotationIntrospector ai = new AnnotationIntrospector();
            Annotation[] annotations;
            Class<User> userClass = User.class;
            String methodDoStuff = "doStuff";
            String fieldId = "id";
            String fieldAddress = "address";
    
            // Find class annotations
            annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
            System.out.println("Annotation on class '" + userClass.getName()
                    + "' are:");
            showAnnotations(annotations);
    
            // Find method annotations
            annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
            System.out.println("Annotation on method '" + methodDoStuff + "' are:");
            showAnnotations(annotations);
    
            // Find field annotations
            annotations = ai.findFieldAnnotation(User.class, fieldId);
            System.out.println("Annotation on field '" + fieldId + "' are:");
            showAnnotations(annotations);
    
            annotations = ai.findFieldAnnotation(User.class, fieldAddress);
            System.out.println("Annotation on field '" + fieldAddress + "' are:");
            showAnnotations(annotations);
    
        }
    
        public static void showAnnotations(Annotation[] ann) {
            if (ann == null)
                return;
            for (Annotation a : ann) {
                System.out.println(a.toString());
            }
        }
    
    }
    

    Hope it helps...

    ;-)

    0 讨论(0)
  • 2020-11-29 00:50

    You have to use reflection to get all the member fields of User class, iterate through them and find their annotations

    something like this:

    public void getAnnotations(Class clazz){
        for(Field field : clazz.getDeclaredFields()){
            Class type = field.getType();
            String name = field.getName();
            field.getDeclaredAnnotations(); //do something to these
        }
    }
    
    0 讨论(0)
  • 2020-11-29 00:53

    You can get annotations on the getter method:

    propertyDescriptor.getReadMethod().getDeclaredAnnotations();
    

    Getting the annotations of a private field seems like a bad idea... what if the property isn't even backed by a field, or is backed by a field with a different name? Even ignoring those cases, you're breaking abstraction by looking at private stuff.

    0 讨论(0)
提交回复
热议问题