【发布时间】:2020-11-06 13:29:46
【问题描述】:
我有一个具有 system.out 的方法,它在 main 中使用。如何拦截该打印并将其分配给 String 变量?我也不希望它被打印出来。
public void print()
System.out.println("hello");
---main---
print(); // need to intercept this
String str = print(); // need assign the contents of the print() to str and not show the contents of print in the console
编辑:由于某些限制,我无法创建 .txt,也无法更改方法的代码。我需要在 main 中进行所有更改
【问题讨论】:
-
将其设置为指向
StringWriter的PrintWriter -
@dan1st 对不起,你能详细说明一下代码吗?
-
如果可能,请更改代码以免使用任何全局状态。 (否则,
System.setOut。) -
@TomHawtin-tackline 哪个代码?我不确定你所说的全局状态是什么意思
-
@Ernest 使用
System.out的代码。将其替换为将打印到传入的PrintStream对象(或类似类型的对象)的代码。 /全局状态通常以static变量的形式隐藏在某处。它只是意味着不是本地的变量状态。