Search code examples
javaprocessjvmclassloader

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.

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. 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). I tried with a class loader but it doesn't work just shares the same console and closing 1 closes the other. 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. but i found out that calling main from 1 class isn't special like when the class loader does it when launching.

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. 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.


Solution

  • Try this in your Class1:

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

    This is gonna start a new console and run your Class2.java.

    You may need something different than /c, depends what you want, check this out.