我在java中写了一些行来运行来自资源的jar文件
首先我得到了jar填充
// create FileInputStream object InputStream fileInputStream = TestCL.class.getResourceAsStream("test.jar");
创建字节数组
byte rawBytes[] = new byte[fileInputStream.available()];
以字节数组
读取文件的内容fileInputStream.read(rawBytes);
我如何从这个fileInputStream加载主类
这是我从类调用方法的测试,我怎么能用jar文件制作这个例子?
package testcl;
import java.io.InputStream;
public class TestCL extends ClassLoader {
public static void main(String args[]) throws Exception {
TestCL javaClassLoader = new TestCL();
javaClassLoader.load();
}
public void load() throws Exception {
// create FileInputStream object
InputStream fileInputStream = TestCL.class.getResourceAsStream("ClassLoaderInput.class");
byte rawBytes[] = new byte[fileInputStream.available()];
fileInputStream.read(rawBytes);
// Load the target class
Class<?> regeneratedClass = this.defineClass(rawBytes, 0, rawBytes.length);
// Getting a method from the loaded class and invoke it
regeneratedClass.getMethod("printString", null).invoke(regeneratedClass.newInstance(), null);
}
}
答案 0 :(得分:0)
尝试加载类并调用main方法或尝试从cmd运行它。
试试这段代码:
Class<?>[] cArgs = new Class[1];
cArgs[0] = java.lang.String.class;
URL url = new URL("// enter the .jar path");
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
InputStream fileInputStream = cl.getResourceAsStream("test.jar");
Method mainMethod = cl.loadClass("//enter class name").getMethod("main", cArgs[0]);