如何获得成员variables的注释?

我想知道一个类的某些成员variables的注释,我使用BeanInfo beanInfo = Introspector.getBeanInfo(User.class)来内省一个类,并使用BeanInfo.getPropertyDescriptors()来查找特定的属性,并使用Class type = propertyDescriptor.getPropertyType()来获得属性的类。

但我不知道如何获得注释添加到成员variables?

我尝试了type.getAnnotations()type.getDeclaredAnnotations() ,但都返回类的注释,而不是我想要的。 例如 :

 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 { ... } 

我想获得地址的注释:@Column,而不是类Address的注释(@Entity,@Table,@Cache)。 如何实现它? 谢谢。

这是代码mkoryak的变体,除了它不依赖于Class.newInstance (和它编译)。

 for(Field field : cls.getDeclaredFields()){ Class type = field.getType(); String name = field.getName(); Annotation[] annotations = field.getDeclaredAnnotations(); } 

另见: http : //docs.oracle.com/javase/tutorial/reflect/class/classMembers.html

每个人都会用注释来描述问题,但是问题在于注释的定义。 您应该添加到注释定义@Retention(RetentionPolicy.RUNTIME)

 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyAnnotation{ int id(); } 

如果您需要知道是否存在特定的注释。 你可以这样做:

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

等其他注释…

我希望能帮助别人。

您必须使用reflection来获取User类的所有成员字段,遍历它们并find它们的注释

像这样的东西:

 public void getAnnotations(Class clazz){ for(Field field : clazz.getDeclaredFields()){ Class type = field.getType(); String name = field.getName(); field.getDeclaredAnnotations(); //do something to these } } 

您可以在getter方法上获得注释:

 propertyDescriptor.getReadMethod().getDeclaredAnnotations(); 

获得一个私人领域的注释似乎是一个坏主意……如果该属性甚至没有一个字段的支持,或者是由不同名称的字段作为后盾呢? 即使忽略这些情况,你也是通过查看私人内容来打破抽象。

 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(){ } } 

和一个testing课:

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

希望能帮助到你…

😉

我的方式

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

或者你可以试试这个

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

希望这会有所帮助。