[ JAVA ] 동적으로 class , method 실행 시킬 수 있는 reflection 사용법
String 문자열 형태로 class 나 method 를 불러서 쓸 수 있다면 참 좋을 것이다.
예를 들어
MyClass 라는 class 가 지금 당장 사용되어야 하는데
이게 상황에 변화에 따라 내일은 YourClass 라는 클래스로 변경되어야 한다고 한다면
새로 프로그램을 수정하고 compile 해서 반영하고 해야 할 텐데
class 이름을 text 파일에서 String 형태로 읽어와서 동적으로 클래스가
변경 될 수 있다면 새로 작업을 하지 않아도 될 것이다.
이런 작업을 가능하게 해 주고 우리가 잘 사용하는 spring framework 의 큰
축이 되는 부분이 바로 reflection 이다.
사용법은 아래와 같이 정리 한다.
package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectionTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Class clas =Class.forName("com.test.ReflectionDTO");
Constructor constructor = clas.getConstructor(new Class[]{String.class,String.class});
Object object = constructor.newInstance(new Object[]{"data1_value","data2_value"});
ReflectionDTO rDTO = (ReflectionDTO)object;
System.out.println("data1["+rDTO.getData1()+"]");
System.out.println("data2["+rDTO.getData2()+"]");
//class 이름으로 class 호출 해서 사용하는 예제
Method method = clas.getMethod("getData1", new Class[] {});
//getData1 method에 argument 가 들어간다면 new Class[] 다음에
//형태를 Class 찾는데서 썻던 것과 같이 String.class 이런식으로 써주면 된다.
Object resultObj = method.invoke(object, new Object[] {});
//getData1 method 에 argument 가 있을 경우 new Object[]{"data1_value"} 이런식으로 넣어주면 된다.
System.out.println((String)resultObj);
}catch(Exception e){
e.printStackTrace();
}
}
}
==========================================실행 결과data1[data1_value]
data2[data2_value]
data1_value