如何通过反射从Java字段获取字符串值? [英] How to get string value from a Java field via reflection?
本文介绍了如何通过反射从Java字段获取字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法:
public void extractStringFromField(Class<?> classToInspect) {
Field[] allFields = classToInspect.getDeclaredFields();
for(Field field : allFields) {
if(field.getType().isAssignableFrom(String.class)) {
System.out.println("Field name: " + field.getName());
// How to get the actual value of the string?!?!
// String strValue = ???
}
}
}
当这个运行时,我得到输出喜欢:
When this runs I get output like:
Field name: java.lang.String
现在如何将实际字符串值提取到 strValue
,使用反射?
Now how do I extract the actual string value into strValue
, using reflection?
推荐答案
看起来你需要对类实例的引用。你可以打电话给 并传入引用,将返回值转换为String。
It looks like you need a reference to an instance of the class. You would want to call get and pass in the reference, casting the return to a String.
您可以按如下方式使用get:
You can use get as follows:
String strValue = (String) field.get (objectReference);
这篇关于如何通过反射从Java字段获取字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文