2013-07-24 50 views
0

是否可以從另一個Java程序啓動Java程序,就像我使用另一個Java命令啓動它一樣?當直接從另一個程序調用程序的main()方法時,這兩種執行都通用於。我試圖每個線程有一個Java上下文每個線程有一個「Java上下文」?

插圖:

的src/COM /項目/ ProjectLauncher.java

public class ProjectLauncher { 

    static { 
     PropertyConfigurator.configure("log4j.properties"); 
    } 

    public static void main(String[] args) { 
     Logger.getLogger(ProjectLauncher.class).info("started!"); 
     // Logs well as expected. 
    } 

} 

測試/ COM /項目/ TestProject.java

public class TestProject extends TestCase { 

    public void testProject() { 
     ProjectLauncher.main(null); 
     Logger.getLogger(TestProject.class).info("tested!"); 
     // The above line logs well, while log4j has been initialized in ProjectLauncher. 
     // I would like it to need its own initialization in this class. 
    } 

} 

我嘗試啓動main方法在另一個線程/ runnable中,但記錄器仍由ProjectLauncher初始化。

回答

2

那麼當你啓動一個Java進程時,它就是一個新的JVM實例。如果你想啓動另一個JVM實例,那麼你需要開始一個單獨的進程。

List<String> command = new ArrayList<String>(); 
    command.add("java"); 
    command.add("ProjectLauncher"); 
    ProcessBuilder builder = new ProcessBuilder(command); 
    builder.redirectErrorStream(true); 
    final Process process = builder.start(); 
     try { 
      process.waitFor(); 
     } catch (InterruptedException ex) { 
      ex.printStackTrace(); 
     } 
     //if you wish to read the output of it then below code else you can omit it. 
     InputStream is = process.getErrorStream(); 
     InputStreamReader isr = new InputStreamReader(is); 
     BufferedReader br = new BufferedReader(isr); 
     String line; 
     while ((line = br.readLine()) != null) { 
      Logger.getLogger(MyClass.class.getName()).severe(line); 
     } 

在上面我們最終開始一個新的過程,在現實中是java ProjectLauncher。如果該類尚未編譯,那麼您將不得不編譯它類似於上面,但使用javac而不是javaProjectLauncher.java而不是等。

相關問題