2011-05-17 77 views

回答

2

有趣的問題。可能有許多工具可以做類似的事情,但不完全是你想要的。當然,ASM會很容易實現。實際上,我使用反射掀起了一個:

public class C { 
    public static void main(String[] args) throws java.io.IOException { 
     java.util.jar.JarFile jar = new java.util.jar.JarFile(args[0]); 
     java.util.Enumeration<java.util.jar.JarEntry> jarEntries = jar.entries(); 
     while (jarEntries.hasMoreElements()) { 
      java.util.jar.JarEntry jarEntry = jarEntries.nextElement(); 
      String jarEntryName = jarEntry.getName(); 
      if (!jarEntryName.endsWith(".class")) { 
       continue; 
      } 
      int jarEntryNameSuffixIndex = jarEntryName.length() - 6; 
      String binaryName = jarEntryName.substring(0, jarEntryNameSuffixIndex).replaceAll("/", "\\."); 
      Class<?> type = null; 
      while (type == null) { 
       try { 
        type = ClassLoader.getSystemClassLoader().loadClass(binaryName); 
       } catch (ClassNotFoundException e) { 
        int binaryNameQualifiedIndex = binaryName.indexOf("."); 
        if (binaryNameQualifiedIndex == -1) { 
         throw new RuntimeException("couldn't load class for " + jarEntryName); 
        } else { 
         binaryName = binaryName.substring(binaryNameQualifiedIndex + 1); 
        } 
       } 
      } 
      int typeModifiers = type.getModifiers(); 
      if (!(java.lang.reflect.Modifier.isPublic(typeModifiers) || java.lang.reflect.Modifier.isProtected(typeModi$ 
       continue; 
      } 
      String packageName = (type.getPackage() == null) ? "" : type.getPackage().getName(); 
      String typeName = type.getCanonicalName(); 
      for (java.lang.reflect.Method method : type.getDeclaredMethods()) { 
       if (method.isSynthetic() || method.isBridge()) { 
        continue; 
       } 
       int methodModifiers = method.getModifiers(); 
       if (!(java.lang.reflect.Modifier.isPublic(methodModifiers) || java.lang.reflect.Modifier.isProtected(me$ 
        continue; 
       } 
       String methodName = method.getName(); 
       System.out.print(packageName + ", " + typeName + ", " + methodName + ", "); 
       for (Class<?> parameterType : method.getParameterTypes()) { 
        String parameterTypeName = parameterType.getCanonicalName(); 
        System.out.print(":" + parameterTypeName + ", "); 
       } 
       Class<?> returnType = method.getReturnType(); 
       String returnTypeName = returnType.getCanonicalName(); 
       System.out.println(returnTypeName); 
      } 
     } 
    } 
} 

將JAR(及其依賴項)包含在類路徑中。這將不會打印參數的名稱,因爲您無法通過反射來獲取這些參數。它也不顯示類型參數或var-args,儘管你可以得到它們。

+0

很不錯的解決方案,雖然我更喜歡它,如果功能被分成幾種不同的方法。但是你正在按照我自己的方式做所有事情(+1) – 2011-05-17 10:08:19

+0

@ Sean:是的,只是一個大腦轉儲。肯定可以使用一些重構。 – 2011-05-17 10:10:11

+0

感謝彌敦道非常有幫助。有沒有辦法來獲取參數名稱和類型? – 2011-05-17 11:50:05

相關問題