Reflect



  
  
  
  
  1. import java.lang.reflect.Method; 
  2.  
  3. public class InvokeTester 
  4.     public int add(int param1, int param2) 
  5.     { 
  6.         return param1 + param2; 
  7.     } 
  8.  
  9.     public String echo(String message) 
  10.     { 
  11.         return "hello: " + message; 
  12.     } 
  13.  
  14.     public static void main(String[] args) throws Exception 
  15.     { 
  16.         Class<?> classType = InvokeTester.class
  17.  
  18.         Object invokeTester = classType.newInstance(); 
  19.  
  20.         // System.out.println(invokeTester instanceof InvokeTester); // true 
  21.  
  22.         Method addMethod = classType.getMethod("add"new Class[] { int.class,int.class }); // add int  
  23.          
  24.         Object result = addMethod.invoke(invokeTester, new Object[]{12});  // , 1,2 InvokeTester.Class invokeTester add 。 。 
  25.          
  26.         System.out.println((Integer)result); 
  27.          
  28.         System.out.println("---------------------"); 
  29.          
  30.         Method echoMethod = classType.getMethod("echo"new Class[]{String.class}); 
  31.          
  32.         Object result2 = echoMethod.invoke(invokeTester, new Object[]{"tom"}); 
  33.          
  34.         System.out.println((String)result2); 
  35.     } 
  36. }