목차

Java Reflection

Field/Method 선언 순서

Accessing Private Field

PrivateObject privateObject = new PrivateObject("The Private Value");
 
Field privateStringField = PrivateObject.class.
            getDeclaredField("privateString");
 
privateStringField.setAccessible(true);
 
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);

Accessing private method

PrivateObject privateObject = new PrivateObject("The Private Value");
 
Method privateStringMethod = PrivateObject.class.
        getDeclaredMethod("getPrivateString", null);
 
privateStringMethod.setAccessible(true);
 
String returnValue = (String)
        privateStringMethod.invoke(privateObject, null);
 
System.out.println("returnValue = " + returnValue);

Class.isAssignableFrom()

A.class.isAssignableFrom(B.class)A a = new B()가 가능한지를 묻는 것이라고 보면된다.

assertThat(Serializable.class.isAssignableFrom(String.class)).isTrue();
assertThat(String.class.isAssignableFrom(Serializable.class)).isFalse();

private static final 필드 읽기/변경

class MyClass4 {
 
    private static final Boolean enabled = Boolean.FALSE; // 읽고 변경할 대상 필드
 
    public static Boolean getEnabled() {
        return enabled;
    }
}
 
// "enabled" 필드 인스턴스 확보
Field field = MyClass4.class.getDeclaredField("enabled");
field.setAccessible(true); // Suppress Java language access checking
 
// "final" modifier 제거
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
 
// 값 읽기
Boolean fieldValue = (Boolean) field.get(null);
System.out.println(fieldValue); // -> false
 
// 값 쓰기
field.set(null, Boolean.TRUE);
System.out.println(MyClass4.getEnabled()); // -> true