如何从 Java 中的不同类读取私有字段的值? [英] How to read the value of a private field from a different class in Java?

查看:25
本文介绍了如何从 Java 中的不同类读取私有字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在第 3 方 JAR 中有一个设计不佳的类,我需要访问其 私有 字段之一.例如,为什么我需要选择私有字段有必要吗?

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose private field is it necessary?

class IWasDesignedPoorly {
    private Hashtable stuffIWant;
}

IWasDesignedPoorly obj = ...;

如何使用反射获取stuffIWant的值?

How can I use reflection to get the value of stuffIWant?

推荐答案

为了访问私有字段,您需要从类的声明字段中获取它们,然后使其可访问:

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT:正如 aperkins 所评论的那样,访问字段、将其设置为可访问和检索值都可能抛出 Exceptions,尽管您需要注意的唯一检查异常已在上面进行了注释.

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

NoSuchFieldException 如果您请求的字段名称与声明的字段不对应,则会抛出该异常.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

IllegalAccessException 如果该字段不可访问(例如,如果它是私有的并且没有通过遗漏 f.setAccessible(true) 来访问)将被抛出代码>行.

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

可能抛出的 RuntimeExceptions 要么是 SecurityExceptions(如果 JVM 的 SecurityManager 不允许您更改字段的可访问性), 或 IllegalArgumentExceptions,如果您尝试访问一个对象上的字段,而不是该字段的类类型:

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

这篇关于如何从 Java 中的不同类读取私有字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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