您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

是。

  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);
    }
}

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

java 2022/1/1 18:17:42 有527人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶