Search code examples
javaclassprocessprocessbuilder

Use process builder to initiate class?


I was wondering if it's possible in java to use a process builder to initiate an instance of a class..

Like

ProcessBuilder pb = new ProcessBuilder(new OtherClass());
Process my_other_class = pb.start();

Or something like that.. Is this even possible..?


Solution

  • ProcessBuilder is for initiating another Process or in short, for launching a new copy of a program.

    To run another public static void main(String[] args) method you will need to combine ProcessBuilder with the java command line argument and all of its parameters (class path, etc). This will create a new instance of that class, in another JVM

    To create another instance of a class in the same JVM, you simply need to call new ClassName(parameters);

    If you want the new class to run independent of the launching block of code, then you will need to make sure the class implements Runnable or extends Thread and is launched appropriately; however, the initialization is still done in the constructor.

    Since both instances are initialized by the code in their constructors, it is not clear what kind of initialization you are seeking. All classes are intialized in their constructor(s), so adding ProcessBuilder seems like a confusing "red herring".