如何从Java中的其他类读取私有字段的值?
我在第3方中设计的课程很差JAR
,我需要访问它的一个私有字段。例如,为什么我需要选择私有字段?
class IWasDesignedPoorly { private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
如何使用反射获取值stuffIWant
?
回答:
为了访问私有字段,你需要从类的声明字段中获取它们,然后使其可访问:
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldExceptionf.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
编辑:正如aperkins
所说,访问字段,将字段设置为可访问并检索值都可能引发Exceptions
,尽管上面需要注释的唯一检查异常。
在NoSuchFieldException如果你问一个字段由不符合声明的字段的名称将被抛出。
obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
该IllegalAccessException
会如果字段是不可访问(被抛出例如,如果是私人和通过失踪了尚未作出访问f.setAccessible(true)
线。
该RuntimeException
可抛出s为要么SecurityExceptionS
(如果JVM的SecurityManager
将不允许你改变一个字段的可访问性),或IllegalArgumentExceptionS
,如果你尝试接入领域的对象不是字段的类的类型上:
f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
以上是 如何从Java中的其他类读取私有字段的值? 的全部内容, 来源链接: utcz.com/qa/424156.html