<< 2006/02/25 | Home | 2006/02/27 >>
PR: 転職    転職    合宿免許    漫画    シルバー    ブライダルエステ    墓地・霊園    葬式   

猫ページ

猫ページ更新完了。

[備忘録] 見えないフィールドにアクセス。

ユニットテストの時に、外からは直接見えないフィールドにアクセスする。

    @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);
このサイトの掲載内容は私自身の見解であり、必ずしもIBMの立場、戦略、意見を代表するものではありません。
日本アイ・ビー・エム 花井 志生 Since 1997.6.8