2012-08-06 572 views
2

我想创建我的规则。我看到这个链接:http://checkstyle.sourceforge.net/writingchecks.html 我创建一个简单的Maven项目,它只包含一个类:如何运行自定义checkstyle规则?

package com.posco.myapp; 
import com.puppycrawl.tools.checkstyle.api.*; 
public class MethodLimitCheck extends Check{ 

private static final int DEFAULT_MAX = 30; 
    private int max = DEFAULT_MAX; 

    @Override 
    public int[] getDefaultTokens() 
    { 
     return new int[]{TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF}; 
    } 

    @Override 
    public void visitToken(DetailAST ast) 
    { 
     // find the OBJBLOCK node below the CLASS_DEF/INTERFACE_DEF 
     DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); 
     // count the number of direct children of the OBJBLOCK 
     // that are METHOD_DEFS 
     int methodDefs = objBlock.getChildCount(TokenTypes.METHOD_DEF); 
     // report error if limit is reached 
     if (methodDefs > this.max) { 
      log(ast.getLineNo(), 
       "too many methods, only " + this.max + " are allowed"); 
     } 
     if (methodDefs < this.max) { 
      log(ast.getLineNo(), 
       "too many methods, only " + this.max + " are allowed"); 
     } 
    } 

我把这个代码在我的config.xml文件

<module name="TreeWalker"> 
    <!-- myCheck.      --> 
    <module name="com.posco.myapp.MethodLimitCheck"> 
    </module> 

,然后,我用命令行运行(使用行家来创建myjar这一后):

java -classpath my-core-1.0.jar:checkstyle-5.5-all.jar com.puppycrawl.tools.checkstyle.Main -c config.xml 

的错误是:ClassNotFoundException的:com.puppycrawl.tools.checkstyle.gui.Main

你想要我!

回答

1

如果您使用的是maven,您可以将checkstyle插件添加到maven pom.xml。所以,无论何时你正在构建项目或运行Maven安装,它都会检查checkstyle错误。 Checkstyle设置非常简单,就像在pom.xml中添加一些行一样。

+0

谢谢拉尼,可能你是误解。我想将MyRuleProject导出到jar文件。然后,我将使用以下命令检查另一个不使用maven的项目(或.java文件): java -classpath my-core-1.0.jar:checkstyle-5.5-all.jar com.puppycrawl.tools.checkstyle .Main -c sun_checks.xml -r(myfile) – ryandao 2012-08-06 06:47:55