怪我咯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);
}