2017-07-25 270 views
0

我使用的是內置的規則集strings.xmlunusedcode.xmlUnusedFormalParameter與AvoidDuplicateLiterals在Maven的PMD-插件

<?xml version="1.0"?> 
<ruleset name="Custom ruleset" 
     xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"> 
    <description> 
     The default ruleset 
    </description> 
    <rule ref="rulesets/java/strings.xml"/> 
    <rule ref="rulesets/java/unusedcode.xml"/> 
</ruleset> 

maven-pmd-plugin如下:

<plugin> 
    <groupId>org.apache.maven.plugins</groupId> 
    <artifactId>maven-pmd-plugin</artifactId> 
    <version>3.8</version> 
    <executions> 
     <execution> 
      <id>pmd-check</id> 
      <phase>validate</phase> 
      <goals> 
       <goal>check</goal> 
      </goals> 
     </execution> 
    </executions> 
    <configuration> 
     <printFailingErrors>true</printFailingErrors> 
     <detail>true</detail> 
     <rulesets> 
      <ruleset>${basedir}/src/main/resources/ruleset.xml</ruleset> 
     </rulesets> 
    </configuration> 
</plugin> 

所以,我得到在以下用例中存在以下問題:

 
public class NewClass { 
    private final static String PMD_UNUSED_FORMAL_PARAMETER = "PMD.UnusedFormalParameter"; 

    @SuppressWarnings(PMD_UNUSED_FORMAL_PARAMETER) 
    private void someMethod1(Object parameter1) { 
     System.out.println("someMethod1"); 
    } 

    @SuppressWarnings("PMD.UnusedFormalParameter") 
    private void someMethod2(Object parameter1) { 
     System.out.println("someMethod2"); 
    } 

    @SuppressWarnings("PMD.UnusedFormalParameter") 
    private void someMethod3(Object parameter1) { 
     System.out.println("someMethod3"); 
    } 

    @SuppressWarnings("PMD.UnusedFormalParameter") 
    private void someMethod4(Object parameter1) { 
     System.out.println("someMethod4"); 
    } 

    public static void main(String[] args) { 
     NewClass newClazz = new NewClass(); 
     newClazz.someMethod1(null); 
     newClazz.someMethod2(null); 
     newClazz.someMethod3(null); 
    } 
} 

註釋參數值"PMD.UnusedFormalParameter"出現4次導致AvoidDuplicateLiterals違規。用註釋掉的字符串private final static替換字符串會導致註釋不起作用,從而導致違反UnusedFormalParameter

我不知道PMD的內部結構。作爲一個開箱即用的用戶,看起來很奇怪的是,PMD並沒有用變量的值來代替變量(儘管這可能是一個上下文敏感的任務,它應該可以在靜態代碼分析的範圍內進行,但這很複雜)並且UnusedFormalParameter不排除明顯用於抑制其他檢查的字符串值,並且因爲PMD而僅存在於其中。

我正在使用maven-pmd-plugin 3.8。

回答

1

至於你的問題,目前有兩種方法可以解決此問題:

  1. AvoidDuplicateLiterals允許,可以設置爲true忽略註釋文字一個skipAnnotations屬性。當然,這將忽略所有註釋中的所有文字,而不僅僅是@SuppressWarnings
  2. 所有規則都允許您配置violationSuppressXPath屬性,並且要忽略表達式的XPath表達式。例如,在這種情況下,您可以將其設置爲AvoidDuplicateLiterals規則以忽略@SuppressWarnings上的文字。我相信這樣做的正確表達是//Annotation//Name[@Image = "SuppressWarnings" or @Image = "java.lang.SuppressWarnings"]/..//Literal(你必須對它進行測試,以確保)

我不知道PMD的內部。作爲一個開箱即用的用戶,看起來很奇怪的是,PMD並沒有用變量的值來代替變量(儘管這可能是一個上下文敏感的任務,它應該可以在靜態代碼分析的範圍內進行,但這很複雜)

你說得對,這種行爲目前不支持。我只需要added an issue on Github來跟蹤請求。隨意籌入。