jar文件是一個具有特定模式的zip文件。 您可以使用ZipFile和ZipEntry或其子類JarFile和JarEntry。
這段代碼(自定義類加載器的一個方法)將返回一個包含您需要的每個「類」類型的數組的Map。
public Map<String, List<Class<?>>> loadAndScanJar(File jarFile)
throws ClassNotFoundException, ZipException, IOException {
// Load the jar file into the JVM
// You can remove this if the jar file already loaded.
super.addURL(jarFile.toURI().toURL());
Map<String, List<Class<?>>> classes = new HashMap<String, List<Class<?>>>();
List<Class<?>> interfaces = new ArrayList<Class<?>>();
List<Class<?>> clazzes = new ArrayList<Class<?>>();
List<Class<?>> enums = new ArrayList<Class<?>>();
List<Class<?>> annotations = new ArrayList<Class<?>>();
classes.put("interfaces", interfaces);
classes.put("classes", clazzes);
classes.put("annotations", annotations);
classes.put("enums", enums);
// Count the classes loaded
int count = 0;
// Your jar file
JarFile jar = new JarFile(jarFile);
// Getting the files into the jar
Enumeration<? extends JarEntry> enumeration = jar.entries();
// Iterates into the files in the jar file
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = enumeration.nextElement();
// Is this a class?
if (zipEntry.getName().endsWith(".class")) {
// Relative path of file into the jar.
String className = zipEntry.getName();
// Complete class name
className = className.replace(".class", "").replace("/", ".");
// Load class definition from JVM
Class<?> clazz = this.loadClass(className);
try {
// Verify the type of the "class"
if (clazz.isInterface()) {
interfaces.add(clazz);
} else if (clazz.isAnnotation()) {
annotations.add(clazz);
} else if (clazz.isEnum()) {
enums.add(clazz);
} else {
clazzes.add(clazz);
}
count++;
} catch (ClassCastException e) {
}
}
}
System.out.println("Total: " + count);
return classes;
}
你可以調用'ZipEntry.getName()'看看它是否是'.class'文件嗎?或者你需要分別計算類和接口(和枚舉?)? – DNA 2012-02-16 16:21:48
我需要分別對它們進行計數(另外還知道並非所有.class文件都包含正確的字節碼)。 – 2012-02-16 16:30:51
我們不希望計算帶有錯誤字節碼的.class文件。 – 2012-02-16 16:37:33