在 Java 中捕获特定线程的控制台输出
我知道关于 SO 也有类似的问题,但它们并不能完全解决我的问题.
I realize there are similar questions on SO, but they don't quite solve my problem.
我想要一个方法,给定一个 Class 对象,将调用该 Class(如果存在)上的main"方法,即 public static void main,并捕获该 main 方法的控制台输出.执行调用的类是一个非守护线程.
I would like a method that, given a Class object, will invoke the "main" method, that is to say, public static void main, on that Class (if it exists) and capture the console output of that main method. The class doing the invocation is a non-daemon thread.
我已经有部分代码,但我不确定如何捕获控制台输出,最重要的是,如何仅为 *this 特定线程捕获它.到目前为止,这是我所拥有的:
I have part of the code already, but I'm not sure how to capture the console output, and on top of that, how to only capture it for *this specific thread. Here's what I have so far:
public class Output extends Thread {
private Class testClass;
public Output(Class clazz) {
this.testClass = clazz;
}
private Method getMainMethod(Class clazz) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (isMainMethod(method)) {
return method;
}
}
return null;
}
private Boolean isMainMethod(Method method) {
return (method.getName().equals("main") &&
Modifier.isStatic(method.getModifiers()) &&
method.getReturnType().equals(Void.class));
}
public void run() {
Method mainMethod = null;
if ((mainMethod = getMainMethod(this.testClass)) == null) {
//if there's no static void main method, throw exception
throw new YouFuckedItUpException();
}
mainMethod.invoke(this.testClass, new String[0]);
return heresWhereImStuckIWantToCaptureTheConsoleOutputAndReturnIt();
}
}
我所需要的只是一些代码或指向如何获取所调用方法的 System.out 和 System.err 输出的答案的链接.任何人都可以提供任何帮助将不胜感激.
All I need is some code to, or a link to an answer on how to, capture the System.out and System.err output of the method being invoked. Any help someone can give would be much appreciated.
提前致谢!
这不仅仅用于测试,最终将投入生产.
This is NOT for testing only, this will eventually be something put into production.
EDIT 2:这需要是线程安全的.多个 main 方法可能会被其他线程同时调用,我希望每个线程只捕获自己的特定输出.
EDIT 2: This will need to be thread-safe. Multiple main methods will be invoked by other threads possibly at the same time, and I want each thread to only capture its own specific output.
推荐答案
既然你使用了 main()
方法——你需要它在同一个进程中吗?如果没有,您可以尝试将其创建为一个新进程 (java.lang.Process
).
Since you use the main()
method - do you need it to be in the same process? If not, you may try to create it as a new Process (java.lang.Process
).
Process
类提供了捕获 StdOut
、StdErr
和/或 StdIn
的必要方法.
The Process
class provides the necessary methods to capture StdOut
, StdErr
and/or StdIn
.
注意 由于一切都在自己的进程中运行,因此线程安全应该没有问题.但是,您仍然需要找到 .class 文件(或至少根文件)所在的位置,以便您可以使用 java here.goes.your.ClassName
运行/创建进程.
Note Since everything runs in it's own process, there should be no issues with thread-safety. However you will still have to find the location, the .class file (or at least the root) is located in, so that you can run/create the Process with java here.goes.your.ClassName
.
相关文章