[Java] Reflection
Reflection은 프로그램 실행 중, 즉 런타임(Runtime)에 자기 자신의 구조를 들여다 보고 조작하는 기능이다. 클래스의 이름, 필드, 메서드, 생성자 등의 정보를 코드로 알아내고, 객체를 생성하거나 메서드를 호출 할 수도 있다.
Get XQ’s stories in your inbox
Join Medium for free to get updates from this writer.
일반적인 코드와 비교해보자.
// 일반적인 방식 - Compile시정에 Class를 알고 있음
Person person = new Person();
person.setName("홀길동");
// Reflection 방식 - Runtime에 Class를 알아냄
Class<?> clazz = Class.forName("com.example.demo.Person"); // 문자열로 Class 로딩
Object. obj = clazz.getDeclaredConstructor().newInstance(); // Class 생성
Method method = clazz.getMethod("setName", String.class); // Method 로딩
method.invoke(obj, "김철수"); // Method 호출private 변수 조작 가능
Reflection을 사용하면 Setter가 정의 되어 있지 않은 Class의 private 변수도 조작 가능하다.
package com.example.demo;
public class Person {
private String name = "홍길동";
}public void modifyPrivateVar() {
Person person = new Person();
Field nameField = Person.class.getDeclaredField("name");
nameField.setAccessible(true); // private 객체 접근 허용
String name = (String) nameField.get(person);
System.out.println(name); // 홍깅동
nameField.set(person, "김철수");
System.out.println(nameField.get(person)); // 김철수
}Autowired에서도 사용
Spring Framework의 의존성 주입 방법 중의 필드 주입에서도 Reflection을 사용한다.
package com.example.demo;
@Component
public class Person {
private String name = "홍길동";
public String getName() {
return this.name;
}
}package com.example.demo;
@Component
public class ServiceA() {
@Autowired
private Person person;
public String getPersonName() {
return this.person.getPersonName(); // 홍길동
}
}ServiceA Class에 person private 변수가 선언 되어 있는데 setPersone public 함수가 정의 되어 있지 않다 그리고 ServiceA에 constructor도 선언되어 있지 않다. 그런데도 Autowired로 person변수에 의존성을 주입 시켰다. 즉 Reflection을 사용하여 접근을 한 것이다.

![[X Window][Linux] X 윈도우](https://miro.medium.com/v2/resize:fit:1358/format:webp/0*F4ntxVRVPco1h3Yr.png)




