如何忽略匹配模式 "if (log.isDebugEnabled()) {" 的行的 CheckStyle 规则

How can I ignore a CheckStyle rule for a line matching a pattern "if (log.isDebugEnabled()) {"

我正在使用 CheckStyle 检查大括号的位置,并且通常希望强制左大括号位于行尾并在其后缩进。我有这个工作。例如

if (something_is_true) {
  ...

但是,在非常特殊的日志语句情况下,我想保持紧凑,我想允许

if (log.isDebugEnabled()) { log.debug("my logging statement."); }

记录器的名称可能会更改,但通常该行将包含“isDebugEnabled”。我不想使用 SuppressWarnings 或在调试行周围添加额外的行 - 我希望它们不会干扰代码的视图和流程。

有没有办法通过 checkstyle 配置文件抑制与给定模式匹配的行的警告?

谢谢。

我认为这是 How to disable a particular checkstyle rule for a particular line of code? 的副本。

事实上你有 3 个选择:

  • 使用@SuppressWarning("checkstyle:rule")
  • 禁止 checkstyle-suppressions.xml
  • 中的规则
  • 使用 java 评论中的 @checkstyle rule (N lines)(也适用于 javadoc)

选项完全取决于您的 checkstyle 插件版本,因此最好从已经提出的问题开始研究:

  • How do I Suppress Warnings in CheckStyle?
  • How to suppress all checks for a file in Checkstyle?
  • Ignoring of Checkstyle warnings with annotation @SuppressWarnings

回答了我自己的问题。我在我的 checkstyle 配置文件中添加了一个抑制文件,其中抑制文件包含以下内容:

<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">

<suppressions>
  <suppress-xpath checks="LeftCurly"
    query="//LITERAL_IF[.//METHOD_CALL/DOT/IDENT[@text='isDebugEnabled']]/SLIST"/>
</suppressions>

这将查找所有包含对 isDebugEnabled 调用的引用的 if 语句,并匹配以下以前导左大括号开头的“语句列表”。