2012-01-31 78 views

回答

9

要獲得方法我一個C類調用C.class.getMethods()[i].toString()的。

編輯:獲取參數名稱使用反射API是可能的。

但是,當你用調試信息編譯你的類時,可以從字節碼中提取信息。 Spring使用ASM bytecode engineering library來做它。

有關更多信息,請參閱this answer

0
import java.lang.reflect.Method; 

public class method1 { 
    private int f1(Object p, int x) throws NullPointerException 
    { 
     if (p == null) 
      throw new NullPointerException(); 
     return x; 
    } 

    public static void main(String args[]) 
    { 
     try { 
      Class cls = Class.forName("method1"); 

      Method methlist[] = cls.getDeclaredMethods(); 
      for (int i = 0; i < methlist.length; i++) { 
       Method m = methlist[i]; 
       System.out.println("name = " + m.getName()); 
       System.out.println("decl class = " + m.getDeclaringClass()); 
       Class pvec[] = m.getParameterTypes(); 
       for (int j = 0; j < pvec.length; j++) 
        System.out.println("param #" + j + " " + pvec[j]); 
       Class evec[] = m.getExceptionTypes(); 
       for (int j = 0; j < evec.length; j++) 
        System.out.println("exC#" + j + " " + evec[j]); 
       System.out.println("return type = " + m.getReturnType()); 
       System.out.println("-----"); 
      } 
     } 
     catch (Throwable e) { 
      System.err.println(e); 
     } 
    } 
} 
+0

http://java.sun.com/developer/technicalArticles/ALT/Reflection/ – bmoran 2012-01-31 14:37:15