Java中是否可以通过反射访问私有字段 [英] Is it possible in Java to access private fields via reflection

查看:99
本文介绍了Java中是否可以通过反射访问私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java可以通过反射访问私有字段str吗?
例如获取此字段的值。

Is it possible in Java to access private field str via reflection? For example to get value of this field.

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


推荐答案

是,它绝对是 - 假设您已获得适当的安全权限。如果您从其他班级访问它,请先使用 Field.setAccessible(true)

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.

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 normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

这篇关于Java中是否可以通过反射访问私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆