如何从 Java 反射中获取 String 字段的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17333599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value of String field from Java reflection?
提问by Paul Vargas
I have an object that has a String field. I can obtain this field by calling:
我有一个具有 String 字段的对象。我可以通过调用获取此字段:
Field field = someObj.getClass().getField("strField");
I sett a Field#set(Object)
method, for setting the value of this instance's field, but the respective getter seems to be Field#get(Object)
, which is weird because I would have expected it to be Field#get()
.
我设置了一个Field#set(Object)
方法,用于设置此实例字段的值,但相应的 getter 似乎是Field#get(Object)
,这很奇怪,因为我原以为它是Field#get()
.
How do I obtain the value of the instance's strField
?
如何获取实例的值strField
?
回答by jtahlborn
if you are using java.lang.reflect.Field
, the "setter" is Field.set(Object,Object)
and the "getter" is Field.get(Object)
. in bothcases, the first parameter is the instance on which you want to access the field.
如果您使用的是java.lang.reflect.Field
,则“setter”是Field.set(Object,Object)
“getter” Field.get(Object)
。在这两种情况下,第一个参数是您要访问该字段的实例。
回答by Paul Vargas
Even without the getter or the setter methods for a property, you can change or get the value using an object reference and Java Reflection.
即使没有属性的 getter 或 setter 方法,您也可以使用对象引用和 Java 反射来更改或获取值。
import java.lang.reflect.Field;
public class Bean {
private String strField;
public static void main(String[] args) throws Exception {
Bean bean = new Bean();
Field field = bean.getClass().getDeclaredField("strField");
field.set(bean, "Hello");
System.out.println(field.get(bean));
}
}