用Java(详细模式)打开/关闭println的任何方法 [英] Any way to turn on/off a println in java (verbose mode)

查看:88
本文介绍了用Java(详细模式)打开/关闭println的任何方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,您是否有任何方法可以使println仅在请求时出现,而不是在默认情况下出现?基本上类似于在许多程序中使用 -v为您提供详细模式,并提供正在发生的信息。

Is there any way in Java that you can make a println appear only when requested, not by default? Basically something similar to using "-v" in many programs to give you verbose mode, with information on what is happening.

例如,假设我在其中有一个if语句一个循环和一个简单的println,它告诉我if语句对于循环的每次迭代是否为true。除了不需要时将其注释掉,不需要时将其取消注释,还有其他方法可以打开/关闭它的可见性吗?然后保存它,重新编译,等等。

For example let's say I have an if statement in a loop, and a simple println that tells me whether the if statement evaluates to true for each iteration of the loop. Is there any other way to toggle on/off it's visibility other than commenting it out when I don't need it and uncomment it when I do? Then saving it, recompiling it, etc.

这将使查看程序中正在发生的事情变得容易得多,但是仅当我需要那么多信息时。正如我所说,我基本上是在寻找一种实现详细模式的方法,该模式可以显示打印语句,而无需注释/取消注释保存,重新编译等。Java是否有类似的东西?

It would make it a lot easier to see what is going on in my program, but only when I want that much info. As I said, I am basically looking for a way to implement a "verbose" mode that shows print statements, without having to comment/uncomment save, recompile, etc. Does Java have anything like this?

推荐答案

您最好的选择是使用某种适当的记录器( log4j )。

Your best choice is to use an appropriate logger of some kind (log4j for example).

如果这不可能,则可以使用类似 ...的stdout和stderr。

If that's not possible, you can "consume" the stdout and stderr using something like...

PrintStream nullPrintStream = new PrintStream(new OutputStream() {
    @Override
    public void write(int b) throws IOException {
    }
});
System.setErr(nullPrintStream);
System.setOut(nullPrintStream);

阻止所有输出开始打印。您可以使用代理进程(使用包装在代理 PrintStream 中的当前标准输出)过滤内容,如果更合适的话...

Which prevent ALL output from begin printed. You can use a proxy process (using the current stdout wrapped in a proxy PrintStream) to filter the content if that's more appropriate...

这篇关于用Java(详细模式)打开/关闭println的任何方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆