在 Java 中是否可以通过反射访问私有字段

2022-08-31 09:46:56

在Java中,是否可以通过反射访问私有字段str?例如,获取此字段的值。

class Test
{
   private String str;
   public void setStr(String value)
   {
      str = value;
   }
}

答案 1

是的,它绝对是 - 假设您具有适当的安全权限。如果您从其他类访问它,请先使用。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);
    }
}

不,你通常不应该这样做...它颠覆了该类原作者的意图。例如,在通常可以设置字段或同时更改其他字段的任何情况下,都可能应用验证。您实际上违反了预期的封装级别。


答案 2

是的。

  Field f = Test.class.getDeclaredField("str");
  f.setAccessible(true);//Very important, this allows the setting to work.
  String value = (String) f.get(object);

然后,使用 field 对象获取类实例上的值。

请注意,get 方法经常让人感到困惑。您有该字段,但没有该对象的实例。您必须将其传递给该方法get