구체적인 Class Type을 알지 못해도 해당 Classd의 method, type, variable들에 접근할 수 있도록 해주는 자바 API이며, 컴파일된 바이트 코드를 통해 Runtime에 동적으로 특정 Class의 정보를 추출할 수 있는 프로그래밍 기법이다.
Class class = Class.forName("클래스 이름");
Reflection은 다음과 같은 정보를 가져올 수 있다.
public static void main(String[] args) throws Exception{
// 1. class를 알고 있을 경우
Class car = Car.class;
// 2. class 이름만 알고 있을 경우
Class car = Class.forName("com.reflection.test.Car");
// 3. Default 생성자를 이용한 객체 생성
Car realCar = car.newInstance();
// 4. class에 구현된 interface 확인
Class[] interfaces = car.getInterfaces();
}
public static void main(String[] args) throws Exception{
// 1. 인자가 없는 생성자 가져오기
Constructor constructor = car.getDeclaredConstructor();
// 2. String 인자를 가진 생성자 가져오기
Constructor constructor = car.getDeclaredConstructors(String.class);
// 3. 모든 생성자 가져오기
Constructor constructors[] = car.getDeclaredConstructors();
// 4. public 생성자만 가져오기
Constructor constructors[] = car.getConstructors();
// public com.reflection.test.Car();
// public com.reflection.test.Car(java.lang.String)
// 5. 생성자를 이용한 객체 생성
Car realCar = constructor.newInstance();
}