Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open and run a compiled Java file?

Tags:

java

How do I open a .class or .jar file within a Java program? (remember that .jar files may have more than one class with main(String[] args) method)

(individual question from IDE-Style program running )

like image 958
Ky. Avatar asked Jul 25 '26 12:07

Ky.


2 Answers

Here is a quick and dirty dirty hack for running all main methods found in the jar.

import java.io.*;

class JarRunner {

    public static void main(String[] args) throws IOException,
                                                  ClassNotFoundException {

        File jarFile = new File("test.jar");
        URLClassLoader cl = new URLClassLoader(new URL[] {jarFile.toURL() });
        JarFile jf = new JarFile(jarFile);

        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry je = entries.nextElement();
            String clsName = je.getName();

            if (!clsName.endsWith(".class"))
                continue;

            int dot = clsName.lastIndexOf('.');
            Class<?> clazz = cl.loadClass(clsName.substring(0, dot));
            try {
                Method m = clazz.getMethod("main", String[].class);
                m.invoke(null, (Object) new String[0]);
            } catch (SecurityException e) {
            } catch (NoSuchMethodException e) {
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
    }
}

As mentioned by other posters, you may want to have a look in the manifest file for the main class (so you don't have to be guessing). This can be accessed through JarFile.getManifest().

like image 92
aioobe Avatar answered Jul 27 '26 00:07

aioobe


The manifest names the jar's entry point.

like image 34
Ignacio Vazquez-Abrams Avatar answered Jul 27 '26 02:07

Ignacio Vazquez-Abrams