如何用checkstyle检查java代码的格式?

下载安装
wget http://umn.dl.sourceforge.net/sourceforge/checkstyle/checkstyle-3.4.tar.gz tar zxvf checkstyle-3.4.tar.gz cd checkstyle-3.4 此时,checkstyle自身及其所需的jar包都在这个目录,平常我们只用checkstyle-all-3.4.jar一个包就可以了。子目录contrib下有几xsl文件,是用于检查结果的样式文件。配置一个检查标准 参考资料2,对如果配置checkstyle作了详细了说明,我这儿用的也是他的配置文件。但ant脚本,建议参考我下面的,他的有一个小错误(我已经在他的文章评论里说了一下。) 进行源代码的自动检查 build.xml的内容如下:
<!DOCTYPE project> <!-- ANT make file checkstype -->现在,运行ant checkstyle-nightly,如果一切正常,你就会在收信方的邮箱里找到相应的邮件了。<!-- See http://jakarta.apache.org/ant for info about ANT -->
<project name="checkstyle" default="checkstyle" basedir=".">
<target name="init"> <tstamp/> <!-- CheckStyle配置,这里你替换成你实际的环境 --> <property name="project.docs.dir"value="${basedir}/contrib" /> <property name="project.src.dir" value="/path/to/your/source/codes" /> <property name="project.checkstyleReport.dir" value="${basedir}/build" /> <property name="checkstyle.jar" value="${basedir}/checkstyle-all-3.4.jar"/> <property name="checkstyle.config" value="${project.docs.dir}/mycheck.xml"/> <property name="checkstyle.report.style" value="${project.docs.dir}/checkstyle-noframes.xsl"/> <property name="checkstyle.result" value="${project.checkstyleReport.dir}/checkstyle_result.xml"/> <property name="checkstyle.report" value="${project.checkstyleReport.dir}/checkstyle_report.html"/> </target> <!--CheckStyle脚步--> <taskdef resource="checkstyletask.properties" classpath="${checkstyle.jar}" /> <target name="checkstyle" depends="init" description=" 对java源代码进行检查并产生检查报告. "> <checkstyle config="${checkstyle.config}" failOnViolation="false" failureProperty="checkstyle.failure"> <formatter type="xml" tofile="${checkstyle.result}"/> <fileset dir="${project.src.dir}" includes="**/*.java"/> </checkstyle> <!-- 生成报告,其格式取决于${checkstyle.report.style} --> <style in="${checkstyle.result}" out="${checkstyle.report}" style="${checkstyle.report.style}"/> </target> <!-- 当有不规范的情况发生时将检查结果发送到 --> <target name="checkstyle-nightly" depends="checkstyle" if="checkstyle.failure" description="Sends email if checkstyle detected code conventions violations."> <mail from="发信方的email" tolist="收信方的email" mailhost="发信方email的服务器" subject=" checkstyle result from project reports" files="${checkstyle.report}"/> </target></project>
- 这个build.xml默认要放chechstyle-3.4那个目录下,checkstyle的配置文件叫mycheck.xml放在contrib子目录下;
- 根据你的ant的安装情况,可能需要将javamail的包复制到$ANT_HOME/lib下。
- Checkstyle Home Page
- Olics, CheckStyle使用详解
- Ant 安装、配置