ユニットテストなどでどうしてもPrivateフィールドに対して外からアクセスしたい時があるかと思います。
以下のようにリフレクションを使用することで外からprivateフィールドにアクセスすることができます。
テスト対象
import org.springframework.stereotype.Component;
@Component
public class PrivateReflection {
private String privateField = "privateField";
}
アクセスするクラス
import java.lang.reflect.Field;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class PrivateReflectionTest {
@Autowired
private PrivateReflection privateReclection;
@Test
public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// 対象クラスのプライベートフィールドのオブジェクトをレフレクションで取得
Field field = this.privateReclection.getClass().getDeclaredField("privateField");
// フィールドへのアクセスを可能にする
field.setAccessible(true);
// フィールドへアクセス
Assert.assertEquals("privateField", field.get(this.privateReclection));
}
}