如何从Java中的不同类读取私有字段的值? [英] How to read the value of a private field from a different class in Java?
问题描述
我在第三方 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 $ c的值$ c>?
推荐答案
为了访问私有字段,你需要从类的声明中获取它们字段然后使它们可访问:
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
编辑:正如 aperkins所评论的那样,访问该字段,将其设置为可访问并检索该值都将抛出异常
s,尽管只有已检查例外需要注意上面的评论。
EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value will all throw Exception
s, 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.
可能抛出的 RuntimeException
是 SecurityException
s(如果JVM的 SecurityManager
将不允许您更改字段的可访问性),或者 IllegalArgumentException
s,如果您尝试访问对象上的字段不是字段类的类型:
The RuntimeException
s which may be thrown are either SecurityException
s (if the JVM's SecurityManager
will not allow you to change a field's accessibility), or IllegalArgumentException
s, 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屋!