我是靠谱客的博主 耍酷飞机,这篇文章主要介绍java 反射 获取字段,如何通过反射从Java字段获取字符串值?,现在分享给大家,希望可以做个参考。

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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部