简体   繁体   English

如何打开并运行已编译的Java文件?

[英]How do I open and run a compiled Java file?

How do I open a .class or .jar file within a Java program? 如何在Java程序中打开.class或.jar文件? (remember that .jar files may have more than one class with main(String[] args) method) (记住.jar文件可能有多个带有main(String [] args)方法的类)

(individual question from IDE-Style program running ) (来自IDE风格程序运行的个别问题)

Here is a quick and dirty dirty hack for running all main methods found in the jar. 这是一个快速而肮脏的脏黑客,用于运行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() . 这可以通过JarFile.getManifest()访问。

Use 采用

java -cp my.jar org.myorg.MyClass

if MyClass is the one you want to start. 如果MyClass是你要开始的那个。 If my.jar has a proper MANIFEST.MF file indicating MyClass you can use 如果my.jar有一个正确的MANIFEST.MF文件,表明你可以使用MyClass

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. 因此,您需要使用反射API来创建必要类的实例并调用其方法。 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. 要确定从jar文件运行的类,您应该使用包'java.util.jar'来通过Manifest类访问清单。 And you can determine entry point of this jar from attribute 'Main-Class'. 您可以从属性“Main-Class”确定此jar的入口点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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