[英]how to load mainclass of jar file called from resource
我在Java中寫了幾行以在運行時從資源中運行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);
}
}
嘗試加載該類並調用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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.