"Preferences"下的PMD项,其中Rules Configuration 项目可以配置PMD的检查规则,自定义检查规则也可以在此通过Import的方式导入到PMD" />

eclipse pmd的使用

您所在的位置:网站首页 java中eclipse的使用方法 eclipse pmd的使用

eclipse pmd的使用

2024-02-26 08:29| 来源: 网络整理| 查看: 265

1

启动Eclipse IDE,打开工程,选择 "Windows"->"Preferences"下的PMD项,其中Rules Configuration 项目可以配置PMD的检查规则,自定义检查规则也可以在此通过Import的方式导入到PMD中

Eclipse中Pmd的安装的安装及配置规则 2

对于不需要的规则,可以选中该规则,点击“remove rule”删除规则,也可以点击“import rule”导入新的规则,配置好后,鼠标右键点击工程中需要检查的JavaSource,

选择PMD-->Find suspect cut and paste。检查结果会放在reports目录下,文件名为cpd-report.txt。

可以通过使用Eclipse的帮助系统来查看PMD插件的文档。

在安装完更新后,如果发生了一个异常,例如”java.lang.RuntimeException: Could not find that class xxxx”,这时试着删除workspace中的.metadata/plugins/net.sourceforge.pmd.eclipse目录下的 ruleset.xml文件。

之后PMD就会通过规则检查你的JavaSource了并且将信息显示在PMD自己的视图上

选择“pmd”-->"check code with pmd",然后进入某个java文件,会出现一些报错,然后你放在上面呢会有一些提示,比如:

android studio的pmd安装使用:

插件下载:http://plugins.jetbrains.com/plugin/4596?pr=androidstudio

使用图解:

              

我就不一一贴图来解释了,请看下面的解释哈,百度文库里面总结的非常实用啊。

1.    Avoidunnecessary Comparisons in Boolean exception.(Boolean类型重复判断)

错误  例子: if(null! = a && a.size>0)

正确       if(null! = a && false == a.IsEmpay())

2. Avoid Usingimplementation types like (ArrayList HashMap/ LinkedHashMap) ,use the interfaceinstand.(用数组的接口类型)

   错误  例子:ArrayList arraylist=newArrayList();

   正确          List     list=newArrayList();

错误  例子: private static HashMap map=new HashMap();

   正确       privatestatic Map map=new HashMap(); 

错误  例子: private static LinkedHashMap map=newLinkedHashMap();

   正确       privatestatic Map map=new LinkedHashMap(); 

3. Method names should not start with capital letters(方法名不能以大写开头)。

错误  例子: public class  Start()

正确      public  class  start() 可以用快捷键 Alt+shift+R全部替

4.varivable      that are final and static should be in allcaps.(定义的参数必须大写)

错误  例子:public static  final  String root

正确      public  static  final String  ROOT

5.Avoidappending charcutars as Strings in StringBuffer append (避免在StringBuffer里附加单个字符时附加成String类型)

错误  例子: buf.append(“)”)或者buf.append(“a”)

正确       buf.append(')')或者 buf.append('a')

6.use ArrayList instanded of vector(使用ArrayList替换vector后还是会报错,所以直接改成是以它的接口形式替换)

错误  例子: vectorkeys = new vector(ELE);

正确       List keys = new ArrayList(ELE);   

7. Variables that are not final should not containunderscores (except for underscores in standard prefix/suffix) (变量不是final类型的不能包含下划线)

错误  例子: private int DEAULT_PORT = 8001;

正确        private intDEAULTPORT = 8001;(调用它的所有类都需要改动)

8. Variables should start with a lowercase character(参数必须要以小写开始)

错误  例子: private static intHANDLE_MAX = 200;

正确      private static inthandleMax= 200;

9. Using equalsIgnoreCase() is cleaner than usingtoUpperCase/toLowerCase().equals().

错误  例子:

正确

10. Unnecessary wrapper object creation

错误  例子: intCurPage =Integer.valueOf(curPage).intValue();

正确      intCurPage = Integer.parseInt(curPage);

11. This is aninefficient use of StringBuffer.toString; call StringBuffer.length instead.    错误 If(newPartLen+smsMOCommondArr.toString().getBytes(DB_CHARSET).length>DB_VERCHAR_MAX_LEN + 1) {}

正确 if(newPartLen+(smsMOCommondArr.toString().getBytes(DB_CHARSET)).length>DB_VERCHAR_MAX_LEN + 1) {}  

12. This final field could be made static

错误  例子: private final String urlPrefix = "http://";

正确       private static final StringURL_PREFIX = "http://";

13. The field name indicates a constant but its modifiersdo not

错误  例子: private static StringCONF_NAME = "version";

正确      private static final StringCONF_NAME = "version";

14. System.out.print is used

错误  例子: System.out.println("PartalOneAppender--message=["+message+"]");

正确     //System.out.println("PartalOneAppender--message=["+message+"]");

15. Switch statements should have a default label

错误  例子: switch (Type)

        {

            caseUSER:

                displayType = "USER";

                break;

            caseADMIN:

                displayType = "ADMIN";

                break;

        }

正确       switch (Type)

        {

            caseUSER:

                displayType = "USER";

                break;

            caseADMIN:

                displayType = "ADMIN";

                break;

 default:

        }

16. Substitute calls to size() == 0 (or size() != 0) withcalls to isEmpty()

错误  例子:  if(null==Handlers || 0 ==Handlers.size())

正确        if (null==Handlers ||Handlers.isEmpty())

17. Return an empty array rather than null.

错误  例子: if (null != g && g.length > 0)

        {

            String[] cloneGroups =new String[g.length];

            System.arraycopy(g, 0, cloneGroups, 0,g.length);

            return cloneGroups;

        }

        return null;

}

正确 if (null != g && g.length > 0)

        {

            String[] cloneGroups =new String[g.length];

            System.arraycopy(g, 0, cloneGroups,0, g.length);

            return cloneGroups;

        }

        returnnew String[0];

18. Deeply nested if..then statements are hard to read

原因:  深嵌套的if循环很难读懂。

报错例子  

if (null != portalScriptionInfo &&null != portalScriptionInfo.getChargeInfo()){

if(productId.equals(portalScriptionInfo.getChargeInfo().getSourceChargeId()))

{// 构造orderInfo 对象

portalOrderInfo.setProductId(productId);

productName = chargeInfo.getProductName();

break;

   }

    }

修改后的例子

     if (null != portalScriptionInfo&&null!=portalScriptionInfo.getChargeInfo()&&(productId.equals(portalScriptionInfo.getChargeInfo()

                                           .getSourceChargeId())))

{

  portalOrderInfo.setProductId(productId);

  productName = chargeInfo.getProductName();

   break;

}

19. Caught exception is rethrown, original stack trace maybe lost

原因: 捕捉一个异常后,再从新把异常扔出去,会把以前的异常信息丢掉。

修改: 可以把在此扔出的异常信息以Log日志的形式打印出来。   

例如:  (错误) catch (IOException ioe)

{

 String msg = "Can't open config file: " + xmlFile + " due to: "

                    + ioe;

            throw new IOException(msg);

        }

改正后:catch (IOException ioe)

        {

String msg = "Can't open config file: " + xmlFile + " dueto: "

                    + ioe;

LogFactory.getInstance().logAction(msg);  }

20.Avoid throwing raw Exception types(避免抛出一个生疏的异常类型)

错误  例子: catch (IOException ioe)

 {

           ioe.printStackTrace();

String msg = "Can't open config file: " + xmlFile.getAbsolutePath()+ " dueto: " + ioe;

           throw new Exception(msg);}

正确  catch (IOException ioe)

{

           ioe.printStackTrace();

String msg = "Can't open config file: " + xmlFile.getAbsolutePath()+ " dueto: " + ioe;

LogFactory.getInstance().logAction(msg);}

21. Method call on object which maybe null

错误  例子: if (GroupList ==null && GroupList.size() < 1)

正确      if (GroupList.isEmpty())

22. It is somewhat confusing to have a field name with thesame name as a method.

原因:A 'getX()' method which returns a booleanshould be named 'isX()'  属性名与方法名称相似。

修改:错误 private boolean stopServer;

        public void stopServer() {

       this.stopServer =true;

}

正确  可以把方法名称该换一个名字!

23. Do not use if statements that are always true oralways false

原因:  不要总使用If循环条件是true或者是false。

修改:  (错误的)

StringNameKey = request.getParameter("NameKey");

if (true) {

           request.setAttribute("NameKey", nameKey);

            ReleaseContent releaseContent = newReleaseContent();

           releaseContent.setCatalogId(catalogId);

            User user= super.getUser(request);

            int userType =userInfo.getUserType();

           …………………

(正确的)ift条件是真的就可以去掉if(true)

 String NameKey =request.getParameter("NameKey");

//if (true) {

           request.setAttribute("NameKey", nameKey);

            ReleaseContent releaseContent = newReleaseContent();

           releaseContent.setCatalogId(catalogId);

            User user= super.getUser(request);

            int userType =userInfo.getUserType();

           …………………

24. System.arraycopy is more efficient

报错的例子: for (int i1 = 0; i1



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3