【问题标题】:detect main inside a jar using java code.使用 java 代码检测 jar 中的 main。
【发布时间】:2016-01-25 21:51:20
【问题描述】:

我正在尝试检测 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 中包含多个 pkg 的情况,因为每个包都可以有一个包含 main 的类。

我会很感激任何想法。

【问题讨论】:

标签: java jar


【解决方案1】:

感谢 fvu 的 cmets,我最终得到了以下代码。

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();
}

我删除了使用找到的方法的代码,因为它对这个答案并不重要

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多