【问题标题】:Checkstyle Regexp to catch all console printing in JavaCheckstyle Regexp 以捕获 Java 中的所有控制台打印
【发布时间】:2019-11-11 23:28:11
【问题描述】:

我有这个 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 中使用更好的正则表达式?

【问题讨论】:

  • \b(?:System\.)?(?:out|err)\.(?:print|write|append) 应该可以工作。或者,\b(?:System\.)?(?:(?:out|err)\.)?(?:print|write|append)
  • @WiktorStribiżew 作者的解决方案也抓住了这种情况:PrintStream debug = System.out; debug.print("text");
  • 为什么不直接禁止系统退出并一起犯错,不管他们调用什么方法?
  • 因为还有其他打印方式,例如Throwable#printStackTrace()

标签: java regex checkstyle system.out


【解决方案1】:

如果您不希望人们使用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 的好处,但不要用蛮力尝试。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多