简体   繁体   English

从jar的主类运行第二个代码(jar)

[英]Running second code(jar) from one's jar main class

What I need is to run a jar file which is inside another jar file from my java code. 我需要运行一个jar文件,该文件位于我的Java代码的另一个jar文件中。 I have this turnOffClient.jar file which I put in my ChatSystemClient.jar file and what I want to do is execute(start,run) turnOffClient.jar file from xClient.jar main-class code. 我有这个turnOffClient.jar文件,我将其放入ChatSystemClient.jar文件中,我想要做的是从xClient.jar主类代码执行(启动,运行)turnOffClient.jar文件。 I have tried: 我努力了:

Runtime.getRuntime().exec(this.getClass().getResource("/jars/TurnOffClient.jar").toString());

Also: 也:

TurnOffClient.main(args);

It seems to work but when I close the first java application the second one closes too,which I don't want. 看来可行,但是当我关闭第一个Java应用程序时,第二个也关闭了,这是我不想要的。 My directories: https://imagizer.imageshack.us/v2/253x254q90/856/ztuz.png 我的目录: https : //imagizer.imageshack.us/v2/253x254q90/856/ztuz.png

this is a bad programming practice, instead create a new class that calls both your programs. 这是不好的编程习惯,而是创建一个新类来调用您的两个程序。

Example: 例:

Program a;
Program b;

    a.run();
    while(a.isAlive()){
       if( /*we need to run program b*/){
         b.run();
         break;
       }

    }

Are these graphical applications? 这些是图形应用程序吗? You could make application A (the one that opens application B ) not-truly-close when "closed", but continue to work in the background until application B is actually closed. 您可以使应用程序A (打开应用程序B的应用程序)在“关闭”时不是真正关闭,但是可以继续在后台工作,直到应用程序B真正关闭为止。

When B is launched, the JVM is just instantiating a special class from B (call it BMain ) and calling its public void main(String[] args) method. 启动B时 ,JVM只是从B实例化一个特殊类(称为BMain )并调用其public void main(String[] args)方法。 There is no reason you cannot call that method directly from your own code (instead of via getRuntime().exec() ): 没有理由不能从您自己的代码中直接调用该方法(而不是通过getRuntime().exec() ):

BMain.main("my arguments here");

If your A process does not immediately end when its window is closed (hunt down and eliminate any JFrame.EXIT_ON_CLOSE instances in A , assuming you are using Swing), and it calls B 's main as above, B will run normally even when A is "closed". 如果您的A进程在关闭其窗口时没有立即结束(在假设您正在使用Swing的情况下, JFrame.EXIT_ON_CLOSE并消除A中的任何JFrame.EXIT_ON_CLOSE实例),并且它如上所述调用B的main,则即使A处于运行状态, B也会正常运行已关闭”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM