Search code examples
javaprocessbuilder

Pass object as parameter in ProcessBuilder?


I want to pass two or more object as parameter into the ProcessBuilder for the purpose of run program as seprate process. I tried the following code but it doesn't work.

public static int exec(FTP ftp, Stage stage) throws IOException,
                                               InterruptedException {
        String javaHome = System.getProperty("java.home");
        String javaBin = javaHome +
                File.separator + "bin" +
                File.separator + "java";
        String classpath = System.getProperty("java.class.path");
        String className = Test.class.getCanonicalName();

        ProcessBuilder builder = new ProcessBuilder(
                javaBin, "-cp", classpath, className+" "+ftp+" "+stage);

        Process process = builder.start();
        process.waitFor();
        return process.exitValue();
    }

And Here is the Test.class

public class Test extends Application
{
    String lol = "000";
    public Test(FTP ftp, Stage stage)
    {
        // The logic goes here for those passed parameter
        System.out.println("This is Test");
    }

    @Override
    public void start(Stage arg0) throws Exception 
    {
        // TODO Auto-generated method stub
        arg0.setTitle("Hello there");
        arg0.setWidth(200);
        arg0.setHeight(200);

        arg0.setScene(new Scene(new Pane(new Label(lol)),1000,1000));
        arg0.show();
    }
}

Here Test class is not executing but If I remove those two parameter then only it works. Can somene please tell me how to pass object as parameter?


Solution

  • No, you cannot pass an instance object across a process boundary (well, OK, there is shared memory, but you can't use that in Java, and it's often not the right solution in C either). What you can do is pass messages between processes. Command line arguments are one way, but as you have found they're limited to data that can be serialized as strings.

    The other alternative would be to serialize your objects and deserialize them in the child process. For example, you could open an ObjectOutputStream from the parent to the child's stdin and send arbitrarily complex objects through that. The objects you'd get on the other side would still be copies, though, not the same object identity as the objects in the parent process.