如何打开并运行已编译的Java文件? [英] How do I open and run a compiled Java file?
本文介绍了如何打开并运行已编译的Java文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Java程序中打开.class或.jar文件?
(请记住.jar文件可能有多个带有main(String [] args)方法的类)
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)
(来自IDE-风格程序运行)
推荐答案
这是一个快速而又脏的 hack ,用于运行jar中的所有主要方法。
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) {
}
}
}
}
正如其他海报所提到的,您可能希望查看主类的清单文件(因此您不必猜测)。这可以通过访问 JarFile.getManifest()
。
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()
.
这篇关于如何打开并运行已编译的Java文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文