首先,让我说,任何这种棘手的事情可能很难是有原因的。
如果您真的需要,这种方法可能对您有用。如所写,它假定“java”在调用者的路径上。
概述:
将 Bootstrapper 类声明为 jar 清单中的主类。
引导程序产生另一个进程,我们在“真正的”主类上调用 java(传入任何你想要的命令行参数)。
将子进程 System.out 和 System.err 重定向到引导程序各自的流
等待子进程完成
这是一篇很好的背景文章。
src/main/java/scratch/Bootstrap.java - 这个类在 pom.xml 中定义为 jar 的主类:<mainClass>scratch.Bootstrap</mainClass>
package scratch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Bootstrap {
class StreamProxy extends Thread {
final InputStream is;
final PrintStream os;
StreamProxy(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
os.println(line);
}
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
}
private void go(){
try {
/*
* Spin up a separate java process calling a non-default Main class in your Jar.
*/
Process process = Runtime.getRuntime().exec("java -cp scratch-1.0-SNAPSHOT-jar-with-dependencies.jar -Xmx500m scratch.App");
/*
* Proxy the System.out and System.err from the spawned process back to the user's window. This
* is important or the spawned process could block.
*/
StreamProxy errorStreamProxy = new StreamProxy(process.getErrorStream(), System.err);
StreamProxy outStreamProxy = new StreamProxy(process.getInputStream(), System.out);
errorStreamProxy.start();
outStreamProxy.start();
System.out.println("Exit:" + process.waitFor());
} catch (Exception ex) {
System.out.println("There was a problem execting the program. Details:");
ex.printStackTrace(System.err);
if(null != process){
try{
process.destroy();
} catch (Exception e){
System.err.println("Error destroying process: "+e.getMessage());
}
}
}
}
public static void main(String[] args) {
new Bootstrap().go();
}
}
src/main/java/scratch/App.java - 这是您程序的正常入口点
package scratch;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World! maxMemory:"+Runtime.getRuntime().maxMemory() );
}
}
调用:java -jar scratch-1.0-SNAPSHOT-jar-with-dependencies.jar
返回:
Hello World! maxMemory:520290304
Exit:0