是。
Field f = Test.class.getDeclaredField("str");
f.setAccessible(true);//Very important, this allows the setting to work.
String value = (String) f.get(object);
请注意,get
方法通常会使人们感到困惑。你有该字段,但没有该对象的实例。你必须将其传递给get
方法
是的,绝对是-假设你具有适当的安全权限。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);
}
}
不,你通常不应该这样做……这是在颠覆该类原始作者的意图。例如,很可能在通常可以设置该字段或可以同时更改其他字段的任何情况下应用验证。你实际上违反了预期的封装级别。