I have a method:
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
Now how do I extract the actual string value into strValue, using reflection?
解决方案
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.
You can use get as follows:
String strValue = (String) field.get (objectReference);
最后
以上就是耍酷飞机最近收集整理的关于java 反射 获取字段,如何通过反射从Java字段获取字符串值?的全部内容,更多相关java内容请搜索靠谱客的其他文章。
发表评论 取消回复