我正在尝试检测jar中哪个类包含main或提供的方法名称(如果可能)。
目前我有以下代码
public static void getFromJars(String pathToAppJar) throws IOException{
FileInputStream jar = new FileInputStream(pathToAppJar);
ZipInputStream zipSteam = new ZipInputStream(jar);
ZipEntry ze;
while ((ze = zipSteam.getNextEntry()) != null) {
System.out.println(ze.toString());
}
zipSteam.close();
}
这将允许我在这些包下获取包和类,但我不知道是否有可能在类中获取方法。 此外,我不知道这种方法是否适用于jar中的几个pkgs的情况,因为每个包都可以有一个带有main的类。
我很感激任何想法。
答案 0 :(得分:3)
感谢fvu的评论,我最终得到了以下代码。
public static void getFromJars(String pathToAppJar) throws IOException, ClassNotFoundException
{
FileInputStream jar = new FileInputStream(pathToAppJar);
ZipInputStream zipSteam = new ZipInputStream(jar);
ZipEntry ze;
URL[] urls = { new URL("jar:file:" + pathToAppJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
while ((ze = zipSteam.getNextEntry()) != null) {
// Is this a class?
if (ze.getName().endsWith(".class")) {
// Relative path of file into the jar.
String className = ze.getName();
// Complete class name
className = className.replace(".class", "").replace("/", ".");
Class<?> klazz = cl.loadClass(className);
Method[] methodsArray = klazz.getMethods();
}
}
zipSteam.close();
}
我删除了使用找到的方法的代码,因为这对于这个答案并不重要