在 Java 中是否可以通过反射访问私有字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1555658/
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
Is it possible in Java to access private fields via reflection
提问by Volodymyr Bezuglyy
Is it possible in Java to access private field str via reflection? For example to get value of this field.
在 Java 中是否可以通过反射访问私有字段 str ?例如获取该字段的值。
class Test
{
private String str;
public void setStr(String value)
{
str = value;
}
}
回答by Jon Skeet
Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true)
first if you're accessing it from a different class.
是的,绝对是 - 假设您拥有适当的安全权限。使用Field.setAccessible(true)
第一,如果你从不同的类访问它。
import java.lang.reflect.*;
class Other
{
private String str;
public void setStr(String value)
{
str = value;
}
}
class Test
{
public static void main(String[] args)
// Just for the ease of a throwaway test. Don't
// do this normally!
throws Exception
{
Other t = new Other();
t.setStr("hi");
Field field = Other.class.getDeclaredField("str");
field.setAccessible(true);
Object value = field.get(t);
System.out.println(value);
}
}
And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normallybe set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.
不,你通常不应该这样做......它颠覆了课程原作者的意图。例如,可以在任何可以正常设置字段的情况下进行验证,或者可以同时更改其他字段。您实际上违反了预期的封装级别。
回答by Yishai
Yes.
是的。
Field f = Test.class.getDeclaredField("str");
f.setAccessible(true);//Very important, this allows the setting to work.
String value = (String) f.get(object);
Then you use the field object to get the value on an instance of the class.
然后使用字段对象获取类实例的值。
Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get
method
请注意,get 方法常常让人们感到困惑。您拥有该字段,但没有该对象的实例。你必须把它传递给get
方法
回答by pythonquick
Yes it is possible.
对的,这是可能的。
You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:
您需要使用 getDeclaredField 方法(而不是 getField 方法),以及您的私有字段的名称:
Field privateField = Test.class.getDeclaredField("str");
Additionally, you need to set this Field to be accessible, if you want to access a private field:
此外,如果要访问私有字段,则需要将此字段设置为可访问:
privateField.setAccessible(true);
Once that's done, you can use the get method on the Field instance, to access the value of the str field.
完成后,您可以使用 Field 实例上的 get 方法来访问 str 字段的值。