[英]How to run main(String [] args) from another class (SendMail)
[英]How to run main method with args from another jar?
我想啟動一個我必須使用的* .jar中包含的main(String args [])方法(不要問,我已經受夠了)。
//this is my own class
class MyInitClass {
public static void main(String args[]) {
SomeJar.MainApp("-port", 8080);
}
}
//this is a keen developers class
class MainApp {
public static void main(String args[]) {
//makes use of the arguments, like starting a socket server
}
}
從我自己的類(最好在單獨的線程中)調用這樣的主要方法的最佳方法是什么?
new Thread(new Runnable() {
public void run() {
MainApp.main(new String[] { "-port", "8080" });
}
}).start();
該類是否在另一個jar文件中無關緊要。 只要包含clas的jar在類路徑中,就可以使用它。 main
是一個靜態方法,就像所有其他靜態方法一樣,因此要調用它,請使用類的名稱,然后使用方法的名稱。 它以String數組作為參數,因此您需要將String數組傳遞給它。 因此,假設MainApp
位於MainApp
包中, com.foo.bar
需要
import com.foo.bar.MainApp;
class MyInitClass {
public static void main(String args[]) {
MainApp.main(new String[] {"-port", "8080"});
}
}
這不會在另一個線程中調用主方法(不確定為什么要這樣做)。 如果要執行此操作,請創建一個線程,然后從該線程或Runnable的run()
方法調用MainApp.main()
。
您可以將.jar添加到您的類路徑中,然后只需加載類並調用靜態Main()方法。 即:
String[] args = new String[] {"-port", "8080"};
MainApp.main(args);
有兩種方法:
如果您不介意在進程中運行它,則可以將其作為SomeJava.MainApp.main({“-port”,“ 8080”})來運行...前提是MainApp類正在以這種方式查找參數。
如果您知道為運行該jar傳遞的命令行參數,則可以使用Runtime.exec()執行它
希望能有所幫助。
您可以嘗試使用Process類啟動jar應用程序。
strPath = "java -jar <path>"
Process proc = Runtime.getRuntime().exec(strPath);
strPath將是您的jar文件的路徑。 您可以將其包圍在Thread類中,以使其在單獨的線程中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.