我在第三方JAR
中有一个设计糟糕的类,我需要访问它的private个字段之一.例如
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
如何使用反射获得stuffIWant
的值?
我在第三方JAR
中有一个设计糟糕的类,我需要访问它的private个字段之一.例如
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
如何使用反射获得stuffIWant
的值?
为了访问私有字段,需要从类的declared个字段中获取它们,然后使它们可以访问:
Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
EDIT:正如aperkins所 comments 的那样,访问字段、将其设置为可访问以及检索值都会抛出Exception
秒,尽管上面只对checked个需要注意的异常进行了 comments .
如果您请求的字段的名称与声明的字段不对应,则会抛出NoSuchFieldException
.
obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
如果该字段不可访问(例如,如果它是私有的,并且没有通过错过f.setAccessible(true)
行来访问),则会抛出IllegalAccessException
.
如果JVM的SecurityManager
不允许您更改字段的可访问性,则可能抛出的RuntimeException
是SecurityException
,如果您try 在非字段类类型的对象上访问字段,则抛出的RuntimeException
是IllegalArgumentException
:
f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type