我们在项目中使用checkstyle和PMD,我正在寻找一种方法来在一行中的多个catch之间强制执行换行符,例如
} catch(IOException | IllegalArgumentException ex) {
...
}
应该通过验证失败
} catch(IOException
| IllegalArgumentException ex) {
...
}
应该通过。
我不是在寻找替代方案,比如随机工作的代码格式化程序,它会引入对IDE的依赖。
我们通过Maven使用checkstyle和PMD。
PMD的简单XPath-based rule可以使用此XPath表达式:
<rule name="MultipleCatchTypesOnSeparateLines"
language="java"
message="Use a separate line for each catch type"
class="net.sourceforge.pmd.lang.rule.XPathRule"
<description>TODO</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CatchStatement/FormalParameter[@SingleLine = true()]
]]>
</value>
</property>
<property name="version" value="2.0"/>
</properties>
</rule>
一个更复杂的,可以检测案例的地方,例如3条捕获2条线(应该在3条线上):
<rule name="MultipleCatchTypesOnSeparateLines"
language="java"
message="Use a separate line for each catch type"
class="net.sourceforge.pmd.lang.rule.XPathRule"
<description>TODO</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
for $a in //CatchStatement/FormalParameter
return for $b in (1 to count($a/Type))
return $a[Type[$b][@BeginLine = $a/Type[$b + 1]/@BeginLine]]
]]>
</value>
</property>
<property name="version" value="2.0"/>
</properties>
</rule>
请注意:使用PMD,您无法验证|
字符是否在下一行。此令牌在AST中不可用。