[備忘録] 見えないフィールドにアクセス。
ユニットテストの時に、外からは直接見えないフィールドにアクセスする。
@SuppressWarnings("unchecked")
<T> T getField(Class cls, Object thisObj, String fieldName, Class<T> fieldClass)
throws NoSuchFieldException, IllegalAccessException
{
Field field = cls.getDeclaredField(fieldName);
field.setAccessible(true);
return (T)field.get(thisObj); // unchecked warning
}
例えばFilterInputStreamの"in"フィールド(protected)を覗く。
FilterInputStream fis = new BufferedInputStream(new ByteArrayInputStream(new byte[0])); InputStream in = getField(FilterInputStream.class, fis, "in", InputStream.class);





