java - 请教获取jar包内的方法数的工具,或者能写个main方法!!!
高洛峰
高洛峰 2017-04-17 16:57:18
0
1
714

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
刘奇

I recommend a jar packageorg.reflections, github address: https://github.com/ronmamo/reflections
A similar question on 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);

The example only shows the class level, and the code of the statistical method will be added later.


UPDATE:
I did not pass the test of the above code, sorry! I tried another method, referenced from: http://stackoverflow.com/questions/15720822/how-to-get-names-of-classes-inside-a-jar-file
Using to read the jar package by myself and splice it The form of a Java fully qualified class name.
1.Introduce the target jar into the Java project
2.Run the main method

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

In order to obtain the path of the jar, I referred to this article http://blog.csdn.net/mybackup/article/details/7401704.
So there is a prerequisite here, you need to know the jar class.
Similar main method code:

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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!