0

我正在测试一个应用程序。我的测试很复杂,我产生了 2 个线程,它们启动了 2 个进程构建器,这些构建器产生了 2 个 java 进程。

是否可以编写一个类似于继承的自定义重定向,但在每个输出和错误消息前添加一些内容,以便我知道它的来源。

下面的示例代码:

public class test {


    public static void main(String... args){


        Thread t = new Thread(new testHelper());
        t.start();

        t = new Thread(new testHelper());
        t.start();

    }

}

import java.io.IOException;


    public class testHelper implements Runnable {
        @Override
        public void run() {
            Class klass = testWorker.class;



            System.out.println(klass.getCanonicalName());
            String separator = System.getProperty("file.separator");
            String classpath = System.getProperty("java.class.path");
            String path = System.getProperty("java.home")
                    + separator + "bin" + separator + "java";
            ProcessBuilder processBuilder =
                    new ProcessBuilder(path, "-cp",
                            classpath,
                            klass.getCanonicalName());
            processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
            processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            Process process = null;
            try {
                process = processBuilder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Child Process is done");


        }
    }

public class testWorker {

    public static void main(String ... args) throws InterruptedException {


        System.out.println("Doing some stuff");
        Thread.sleep(10000);
        System.out.println("Finished doing some stuff");



    }

}
4

1 回答 1

1

不,这是不可能的。在java.lang.ProcessBuilder.Redirect的源代码中,构造函数是私有的,有这个说法

/**
 * No public constructors.  Clients must use predefined
 * static {@code Redirect} instances or factory methods.
 */
 private Redirect() {}
于 2014-07-02T16:09:22.563 回答