静态代码扫描工具PMD参数过程简介与JCommander 以及如何扩展

1.前言

PMD是一款优秀的静态代码扫描工具,扩展性也非常好.本文介绍PMD的参数以及如何去扩展.由于前人已经做了参数解析,我就不造轮子了.

  PMD使用手册(内含参数解析) https://www.cnblogs.com/liveandevil/p/3616949.html

  JCommander使用简介   http://hao.jobbole.com/jcommander/

2.正文

 PMD的参数主要分析代码在PMD类的run方法:

1 public static int run(String[] args) {
2        ...
3         final PMDParameters params = PMDCommandLineInterface.extractParameters(new PMDParameters(), args, "pmd");
4         final PMDConfiguration configuration = params.toConfiguration();
5 ...
6 }

首先通过PMDCommandLineInterface.extractParameters把args参数封装到params对象里,然后再由params参数变成configuration对象.

原本我认为应该直接封装到configuration对象里,但实际上应该让configuration类只负责配置属性的最终呈现,而封装过程应该给另一个param类,因为JCommander需要针对每个参数做匹配,而有一些参数并不是最终的configuration里的某一个成员属性.所以要集合在一个类里会造成成员功能不统一,而且代码冗杂.

一开始的从args参数到param的封装就两句话

1 public static PMDParameters extractParameters(PMDParameters arguments, String[] args, String progName) {
2         JCommander jcommander = new JCommander(arguments);//核心
3         jcommander.setProgramName(progName);
4         ...
5         return arguments;
6     }    

实际上从PMD这个运用,也能马上就学会JCommander的使用.

打开PMDParameters类就会发现,

 1 public class PMDParameters {
 2 
 3     @Parameter(names = { "-rulesets", "-R" }, description = "Comma separated list of ruleset names to use.",
 4             required = true)
 5     private String rulesets;
 6 
 7     @Parameter(names = { "-uri", "-u" }, description = "Database URI for sources.", required = false)
 8     private String uri;
 9 
10     @Parameter(names = { "-dir", "-d" }, description = "Root directory for sources.", required = false)
11     private String sourceDir;
12 
13     @Parameter(names = { "-filelist" }, description = "Path to a file containing a list of files to analyze.",
14             required = false)
15     private String fileListPath;

JCommander是运用注解@Parameter的形式,name属性是args参数里的形式,比如-R 就是 args参数里 -R空格 "具体值" ,又比如-R "java-basicRule",此时ruleSets的值就会变成java-basicRule,是不是很简单?

所以如果想从参数上扩展PMD的话,非常简单,先添加一个私有成员,再写上注解Parameter,再提供get/set方法

而params每个属性赋予值后,便在toConfiguration里封装到configuration对象.

3.后文

其实注解的形式在WEB开发里已经非常常见,PMD的这种运用对一直开发WEB应用的我也算是稍微拓展一下眼界.

猜你喜欢

转载自www.cnblogs.com/zhhiyp/p/9147586.html