Reflection Example

다음은  Command 라인에서 입력된 클래스의 메소드를 실행(Invoke)하는 예제이다.

 

package reflect;

 

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

 

class Invoke {

       public static void main(String[] args) {

              try {

                     Class c = Class.forName(args[0]);

                     Method m = c.getMethod(args[1]);

                     Object ret = m.invoke(null);

                     System.out.println("Invoked static method: " + args[1] + " of class: " + args[0]

                                  + " with no args\nResults: " + ret);

 

              } catch (ClassNotFoundException e) {

                     System.out.println(e);

              } catch (NoSuchMethodException e2) {

                     System.out.println(e2);

              } catch (IllegalAccessException e3) {

                     System.out.println(e3);

              } catch (InvocationTargetException e) {

                     System.out.println(e);

                     System.out.println("Method threw an: " + e.getTargetException());

              }

       }

} 

 

% java   java.lang.System   currentTimeMillis

 

결과 : 

Invoked static method: currentTimeMillis of class: java.lang.System with no args

Results: 1360164595776

 

 

'Java > The Java Language' 카테고리의 다른 글

Text Encoding  (0) 2013.10.12
Java Dynamic Proxy --> Draft  (0) 2013.02.07
What is Enum in Java  (1) 2013.02.06
Static and Nostatic Initializer blocks  (0) 2013.02.06
Assertion  (1) 2013.02.06
Posted by Steven J.S Min
,