首頁  >  問答  >  主體

java - 请教获取jar包内的方法数的工具,或者能写个main方法!!!

请教获取jar包内的方法数的工具,请大神帮帮忙

高洛峰高洛峰2718 天前720

全部回覆(1)我來回復

  • 怪我咯

    怪我咯2017-04-17 16:59:18

    我推薦一個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

    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);
    }

    回覆
    0
  • 取消回覆