[英]In Java (7), how to get the value of an annotated field
I have a class with fields on which some are annotated with a custom annotation. 我有一个带有字段的类,其中的一些字段带有自定义注释。 i have a method that needs to retreive the value of those fields in an instantiated class:
我有一种方法需要检索实例化类中那些字段的值:
public void displayStringValue(Row row)
for (Field field : Row.class.getDeclaredFields()) {
SomeAnnotation annotatedElement = field.getAnnotation(SomeAnnotation.class);
if (annotatedElement != null) {
row.getValue(field.getName()); // What to do here in stead of this?
}
}
}
Obviously, row.getValue(String fieldname);
显然,
row.getValue(String fieldname);
does not exist. 不存在。 Here i need to find a way of getting the value of that field in row.
在这里,我需要找到一种获取行中该字段的值的方法。
You want to Field#get()
the value of the field for the given Row
object? 您想
Field#get()
给定Row
对象的字段值吗?
field.setAccessible(true);
Object fieldValue = field.get(row); // or cast it if you know the type
setAccessible(..)
is necessary if the field is not visible from the calling class. 如果在调用类
setAccessible(..)
不到该字段,则需要setAccessible(..)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.