如何通过反射从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 = ???
        }
    }
}
当运行时,我得到如下输出:
Field name: java.lang.String现在我该怎样提取实际字符串值入strValue, 
回答:
看起来您需要引用该类的实例。您可能要调用get和pass的引用,将返回值转换为String。
您可以使用get,如下所示:
String strValue = (String) field.get (objectReference);以上是 如何通过反射从Java字段获取字符串值? 的全部内容, 来源链接: utcz.com/qa/423454.html






