请教获取jar包内的方法数的工具,请大神帮帮忙
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
我推薦一個jar包org.reflections,github位址:https://github.com/ronmamo/reflections一個stackoverflow的類似問題:http://stackoverflow.com/questions/520328/can-you-find-all-classes -in-a-package-using-reflection
org.reflections
Reflections reflections = new Reflections("my.project.prefix"); Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);
範例只展示到類別層級的,後續補上統計方法的程式碼。
UPDATE:上面的程式碼我沒有測試通過,抱歉!我嘗試了另一個方法,參考自:http://stackoverflow.com/questions/15720822/how-to-get-names-of-classes-inside-a-jar-file採用自己讀jar包,拼接Java全限定類別名稱的形式。 1.將目標jar引入到Java工程2.執行main方法
private static List<String> getClassNames(String jarPath) throws IOException { List<String> classNames = new ArrayList<String>(); ZipInputStream zip = new ZipInputStream(new FileInputStream(jarPath)); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { if (!entry.isDirectory() && entry.getName().endsWith(".class")) { // This ZipEntry represents a class. Now, what class does it represent? String className = entry.getName().replace('/', '.'); // including ".class" classNames.add(className.substring(0, className.length() - ".class".length())); } } return classNames; }
為了獲得jar的路徑,我參考了http://blog.csdn.net/mybackup/article/details/7401704 這篇文章。 所以這裡有一個前提,需要知道jar的類別。 類似的main方法程式碼:
public static void main(String[] args) throws ClassNotFoundException, IOException { DB db = new DB(); //某个jar包中的类 String jarPath = db.getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); int count = 0; List<String> names = getClassNames(jarPath); for (String name : names) { System.out.println(name); Class<?> clazz = Class.forName(name); Method[] methods = clazz.getDeclaredMethods(); for(Method m : methods) { System.out.println(m.getName()); //这里可能会有问题哦 count++; } } System.out.println("all count: " + count); }
我推薦一個jar包
org.reflections
,github位址:https://github.com/ronmamo/reflections一個stackoverflow的類似問題:http://stackoverflow.com/questions/520328/can-you-find-all-classes -in-a-package-using-reflection
範例只展示到類別層級的,後續補上統計方法的程式碼。
UPDATE:
上面的程式碼我沒有測試通過,抱歉!我嘗試了另一個方法,參考自:http://stackoverflow.com/questions/15720822/how-to-get-names-of-classes-inside-a-jar-file
採用自己讀jar包,拼接Java全限定類別名稱的形式。
1.將目標jar引入到Java工程
2.執行main方法
為了獲得jar的路徑,我參考了http://blog.csdn.net/mybackup/article/details/7401704 這篇文章。
所以這裡有一個前提,需要知道jar的類別。
類似的main方法程式碼: