您可以使用 ASM 字节码分析库 (http://asm.ow2.org) 为此编写自己的实用程序(阅读本文后一小时内)。您需要实现 ClassVisitor 和 MethodVisitor。您将使用 ClassReader 解析库中的类文件。
- 将为每个声明的方法调用 ClassVisitor 的 visitMethod(..)。
- 将为每个调用的方法调用您的 MethodVisitor 的 visitMethodInsn(..)。
维护一个地图来进行计数。键代表方法(见下文)。这是一些代码:
class MyClassVisitor {
// ...
public void visit(int version, int access, String name, ...) {
this.className = name;
}
public MethodVisitor visitMethod(int access, String name, String desc, ...):
String key = className + "." + name + "#" + desc;
if (!map.containsKey() {
map.put(key, 0);
}
return new MyMethodVisitor(map);
}
// ...
}
void class MyMethodVisitor {
// ...
public visitMethodInsn(int opcode, String name, String owner, String desc, ...) {
String key = owner + "." + name + "#" + desc;
if (!map.containsKey() {
map.put(key, 0);
}
map.put(key, map.get(key) + 1);
}
// ...
}
基本上就是这样。你的节目开始时是这样的:
Map<String,Integer> map = new HashMap<String,Integer>();
for (File classFile : my library) {
InputStream input = new FileInputStream(classFile);
new ClassReader(input).accept(new MyClassVisitor(map), 0);
input.close();
}
for (Map.Entry<String,Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
System.out.println("Unused method: " + entry.getKey());
}
}
享受吧!