Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect main inside a jar using java code.

Tags:

java

jar

I am trying to detect which class inside a jar contains main or a supplied method name (if possible).

At the moment I have the following code

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

This will allow me to get packages and classes under these packages, but I do not know if it is possible to even get methods inside classes. Further, I do not know if this approach is even good for a case of several pkgs inside the jar, since each package can have a class with main in it.

I would appreciate any ideas.

like image 891
Quantico Avatar asked Oct 18 '22 23:10

Quantico


1 Answers

Thanks to fvu's comments, I ended up with the following code.

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

I removed the code that uses the methods found, since it is not important for this answer

like image 179
Quantico Avatar answered Oct 26 '22 23:10

Quantico