首页 > 解决方案 > Checkstyle Regexp 以捕获 Java 中的所有控制台打印

问题描述

我有这个 Checkstyle 块来阻止人们在我的项目中打印到控制台:

<module name="Regexp">
    <property name="format" value="((System\.|(out|err)\.print)|printStackTrace)"/>
    <property name="ignoreComments" value="true"/>
    <property name="illegalPattern" value="true"/>
    <property name="message" value="No printing to console, use a logger."/>
</module>

正则表达式在哪里((System\.|(out|err)\.print)|printStackTrace)

然而,有人偷偷溜进来:out.println 通过导入import static java.lang.System.out;.

所以我将正则表达式更新为:((System\.(out|err))|printStackTrace|(out|err)\.(print|write|append))

我的问题是:这个正则表达式是否涵盖了在 Java 中打印到控制台的所有方式?有没有人有他们在 Checkstyle 中使用的更好的正则表达式?

标签: javaregexcheckstylesystem.out

解决方案


如果您不希望人们使用System.out.println,那么您能做的最好的事情就是争辩他们的工作处于危险之中并用其他对策威胁他们。(拜托,我在开玩笑,永远不要这样做):)

他们可以做类似的事情

import static java.lang.System.out;

public class App 
{
    public interface wvs {
        void abc(Object o);
    }

    static final wvs bwz = out::println;  /* this is the only reference to 
                                           * println, but you can hide it 
                                           * in another part of the 
                                           * application */

    static void blah(wvs o, Object oo)
    {
        o.abc( oo );
    }

    public static void main( String[] args )
    {
        System.out.println( "Hello World!" ); /* this will be filtered */
        blah(bwz, "another message by courtesy of LC"); /* will this? */
    }
}

并让您疯狂地寻找对System.out.println(). 您甚至可以编写一个Logger类以绕过Logger配置打印到控制台。:)

作为提示,永远不要试图用武力证明人类的智慧,你会输的。作为一名优秀的经理,试着说服你的员工按预期行事。让他们相信使用 Loggers 的好处,但不要用蛮力尝试它们。

如果您在一个月内没有看到应用程序的控制台输出,请尝试向他们提供免费啤酒……这几乎总是有效的。


推荐阅读