简体   繁体   中英

How do I open and run a compiled Java file?

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 )

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() .

Use

java -cp my.jar org.myorg.MyClass

if MyClass is the one you want to start. If my.jar has a proper MANIFEST.MF file indicating MyClass you can use

java -jar my.jar

清单命名jar的入口点

您可以使用任何压缩软件(winrar,winzip,7zip)打开.jar,并且可以使用java.exe运行.class文件

I think your questions is about situation when you don't know specification of external class in compilation time. Am I right?

So you need to use reflection API for creating instance of necessary class and invoking its method. You can see example above.

And for determining class for running from jar file you should use package 'java.util.jar' for accessing manifest via Manifest class. And you can determine entry point of this jar from attribute 'Main-Class'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM