简体   繁体   English

如何从另一个类启动一个独立的java类?

[英]How to launch an independent java class from another class?

I need a "main" class that creates other independent class instances.我需要一个创建其他独立类实例的“主”类。 They are independent in that they have their own console and if i close 1 the others don't close.他们是独立的,因为他们有自己的控制台,如果我关闭 1,其他人不会关闭。

example: i have these 2 classes示例:我有这两个类

public class Class1 {

    public static void main(String[] args) {
        new Class1();
    }

    Class1() {
        System.out.println("class1");
        Scanner sc = new Scanner(System.in);
        sc.next(); // just to stop runtime from exiting. it suspends it
    }
}

and

public class Class2 {

    public static void main(String[] args) {
        new Class2();
    }

    Class2() {
        System.out.println("class2");
        Scanner sc = new Scanner(System.in);
        sc.next();  // just to stop runtime from exiting. it suspends it
    }
}

If I launch each one from my IDE I get what I want.如果我从我的 IDE 启动每一个,我就会得到我想要的。 But now i want to get the same only with launching class2 from class1 (actually many class 2 from class 1 but getting 1 will get me the others).但是现在我只想通过从 class1 启动 class2 来获得相同的结果(实际上很多 class 2 从 class 1 但获得 1 会让我得到其他人)。 I tried with a class loader but it doesn't work just shares the same console and closing 1 closes the other.我尝试使用类加载器,但它不能正常工作,只是共享同一个控制台,关闭 1 关闭另一个。 Or I did it wrong.或者我做错了。

Class1() {
    System.out.println("class1");
    try {
        Class<?> c = ClassLoader.getSystemClassLoader().loadClass("test.Class2");
        c.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }
    Scanner sc = new Scanner(System.in);
    sc.next();
}

I don't care if i call the constructor of class 2 or its main method as long as it works.我不在乎我是否调用类 2 的构造函数或其 main 方法,只要它有效。 but i found out that calling main from 1 class isn't special like when the class loader does it when launching.但我发现从 1 个类调用 main 并不像类加载器在启动时那样特殊。

I don;t know if i need a new process, a new VM or a new class loader because i don't know how a console is shared and actually i don't think i know the differences.我不知道我是否需要一个新进程、一个新的 VM 或一个新的类加载器,因为我不知道控制台是如何共享的,实际上我认为我不知道它们之间的区别。 I know that system exit will exit the VM so I think I need to start a new VM?我知道系统退出会退出虚拟机,所以我想我需要启动一个新的虚拟机? Do i have to?我一定要吗? I saw several question on this site on how to do it but it's very ugly and doesn;t look robust.我在这个网站上看到了几个关于如何做的问题,但它非常难看,而且看起来并不健壮。

Try this in your Class1 :在你的Class1试试这个:

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", "java", "Class2");
pb.start();

This is gonna start a new console and run your Class2.java .这将启动一个新控制台并运行您的Class2.java

You may need something different than /c , depends what you want,check this out.您可能需要与/c不同的东西,这取决于您想要什么,请查看。

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

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