[英]How to get attributes of annotations in Java using reflection?
我在java中有几个我想知道的数据类 - 使用反射 - 哪些字段具有具有特定属性的特定注释,如下所示:
@Column(columnDefinition = "text") // Text with unbound length
private String comment;
我想出了如何获取该字段的注释以及它是否属于Column
类型:
private boolean isStringFieldWithBoundLength(Field attr) {
Annotation[] annotations = attr.getDeclaredAnnotations();
for (Annotation ann : annotations) {
Class<? extends Annotation> aClass = ann.annotationType();
if (Column.class == aClass) {
// ...
}
}
}
现在在调试器中,我可以看到aClass
对象包含有关所提供参数的信息。 不幸的是,我不知道如何使用代码访问它。 是否可以在 java 中访问这些信息?
您应该能够使用获取该注释的实例(包括您的值)
Column fieldAnnotation = attr.getAnnotation(Column.class);
如果该字段未使用@Column
注释, getAnnotation
返回 null。 这意味着您不需要遍历attr.getDeclaredAnnotations();
然后,您可以调用fieldAnnotation.columnDefinition()
或您的注释可能具有的任何自定义字段。
另外:您的注释需要有@Retention(RetentionPolicy.RUNTIME)
才能工作,否则您的注释将在编译期间从类/字段/方法中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.