final修飾子のClassのprivateなコンストラクタを呼び出す方法。
単体テストで使う用。
Java SE 1.8 Eclipse4.4 JUnit4 jmockit 1.43
コンストラクタの呼び出し
テスト対象のクラス
package privateConstructor; private class privateConstructor_1 { private privateConstructor_1(){ System.out.println("コンストラクタ"); } }
テストコード
package privateField; import java.lang.reflect.Field; import org.junit.Test; public class privateConstructor_1_Test { @Test public void test() { Class<PrivateConstructor_1> targetClass=PrivateConstructor_1.class; Constructor<PrivateConstructor_1> targetConstructor=(Constructor<PrivateConstructor_1>) targetClass.getDeclaredConstructor(); targetConstructor.setAccessible(true); PrivateConstructor_3 refrectedClass=targetConstructor.newInstance(); } }
実行結果
コンストラクタ
privateフィールドの呼び出し
privateなコンストラクタを持つfinal修飾子のClassのフィールドを呼び出す方法 テスト対象のクラス
package privateConstructor; public class privateConstructor_1 { public privateConstructor_1(){ System.out.println("コンストラクタ"); } private int privateField1=0; }
テストコード
package privateField; import java.lang.reflect.Field; import org.junit.Test; public class privateConstructor_1_Test { @Test public void test() { Class<PrivateConstructor_1> targetClass=PrivateConstructor_1.class; Constructor<PrivateConstructor_1> targetConstructor=(Constructor<PrivateConstructor_1>) targetClass.getDeclaredConstructor(); targetConstructor.setAccessible(true); Field targetField=targetClass.getDeclaredField("privateField1"); targetField.setAccessible(true); PrivateConstructor_3 refrectedClass=targetConstructor.newInstance(); System.out.println(targetField.get(refrectedClass)); } }
実行結果
コンストラクタ 0
備忘録として残してます。