How to get annotations of a member variable?

I want to know a class with some member variable comments, I use BeanInfo beanInfo = Introspector.getBeanInfo(User.class) to introspect the class and use BeanInfo.getPropertyDescriptors() to find a specific property and use Class type = propertyDescriptor.getPropertyType() for get the Class property.

But I don't know how to add annotations to a member variable?

I tried type.getAnnotations() and type.getDeclaredAnnotations() , but both return class annotations, not what I want. For example:

 class User { @Id private Long id; @Column(name="ADDRESS_ID") private Address address; // getters , setters } @Entity @Table(name = "Address") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) class Address { ... } 

I want to get the address annotation: @Column, not the Address annotation class (@Entity, @Table, @Cache). How to reach it? Thank.

+44
java reflection annotations
Dec 15 '10 at 17:48
source share
8 answers

This is a variant of the mkoryak code, except that it does not rely on Class.newInstance (and compiles).

 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

+59
Dec 15 '10 at 20:55
source share

Everyone describes the problem with getting annotations, but the problem is identifying your annotation. You must add a @Retention(RetentionPolicy.RUNTIME) annotation to the definition:

 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyAnnotation{ int id(); } 
+70
Sep 08 '12 at 7:19
source share

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

  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 other annotations ...

I hope to help someone.

+10
May 09 '13 at 18:05
source share

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

something like that:

 public void getAnnotations(Class clazz){ for(Field field : clazz.getDeclaredFields()){ Class type = field.getType(); String name = field.getName(); field.getDeclaredAnnotations(); //do something to these } } 
+8
Dec 15 '10 at 17:51
source share

You can get annotations for the getter method:

 propertyDescriptor.getReadMethod().getDeclaredAnnotations(); 

Getting private field annotations seems like a bad idea ... what if a property is not even supported by a field or is not supported by a field with a different name? Even ignoring these cases, you break the abstraction by looking at private things.

+4
Dec 15 '10 at
source share
 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 the 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 this helps ...

; -)

+2
Dec 24 '10 at 9:10
source share

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
Dec 15 '15 at 9:00
source share

Or you can 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 helps.

-2
Mar 07 '13 at 14:35
source share



All Articles