怪我咯2017-04-17 16:59:18
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);
}