invoke,java.lang.reflect.Method,Dynamic Method
비지니스 로직에 따라 특정 Class의 특정 Method 를 동적으로 할당하여 호출해야할 경우가 있다.
이 경우, 아래와 같은 수순으로 호출하여 실행할수 있다.
javascript,asp,php의 eval과 유사한 맥락으로 이해하면 된다.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestDynaMethod {
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Shortcut
String rtn = (String) (((new TestCls()).getClass()).getMethod("getApple", new Class[] {})).invoke((new TestCls()), new Object[] {});
System.out.println(rtn);
// type 2
Class cls = (new TestCls()).getClass();
Method m = cls.getMethod("getOrange", new Class[] {});
System.out.println(m.invoke((new TestCls()), new Object[] {}));
}
}
class TestCls {
public String getApple() {
System.out.println("Apple");
return "아쁠";
}
public String getOrange() {
System.out.println("Orange");
return "어린쥐";
}
}