本文主要是介绍IDEA使用CheckStyle代码规范,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
IDEA使用CheckStyle代码规范说明
前言:
CheckStyle是SourceForge下的一个项目,提供了一个帮助JAVA开发人员遵守某些编码规范的工具。它能够自动化代码规范检查过程,从而使得开发人员从这项重要,但是枯燥的任务中解脱出来。
CheckStyle检验的主要内容
·Javadoc注释
·命名约定
·标题
·Import语句
·体积大小
·空白
·修饰符
·块
·代码问题
·类设计
·混合检查(包括一些有用的比如非必须的System.out和printstackTrace)
从上面可以看出,CheckStyle提供了大部分功能都是对于代码规范的检查,而没有提供像PMD和Jalopy那么多的增强代码质量和修改代码的功能。但是,对于团队开发,尤其是强调代码规范的公司来说,它的功能已经足够强大。
第一步 下载CheckStyle-IDEA插件
点击Browse repositories–>再搜索CheckStyle–>找到CheckStyle-IDEA–>再点击Install–>自动安装完成后重启
第二步 导入规则文件
找到Other Settings –>点击Checkstyle–>再点击Configuration File的加号
先填写规则描述名–>然后点击Browse导入规则文件–>点击Next–再点击Finish
(或者是自带的谷歌和sun的规范)
第三步 使用
点击状态栏上的CheckStyle按钮,点击(红叉按钮下)旁边的Check project 或者check Module按钮,检查工程的不规则编码和习惯
双击不规范列表的一条数据,直接进入界面修改不规范代码
如果需要界面不报异常红,勾选Treat Checkstyle errors as warnings,最后重启工程或AS
备注一:
Check.xml
代码示例
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"><!-- sumavision代码格式检查 --><module name="Checker"> <property name="charset" value="UTF-8" /> <property name="severity" value="warning" /> <module name="TreeWalker"> <!-- Checks for imports --> <!-- 必须导入类的完整路径,即不能使用*导入所需的类 --> <module name="AvoidStarImport" /> <!-- 检查是否从非法的包中导入了类 illegalPkgs: 定义非法的包名称 --> <module name="IllegalImport" /> <!-- defaults to sun.* packages --> <!-- 检查是否导入了不必显示导入的类 --> <module name="RedundantImport" /> <!-- 检查是否导入的包没有使用 --> <module name="UnusedImports" /> <!-- Checks for Naming Conventions. 命名规范 --> <!-- local, final variables, including catch parameters --> <module name="LocalFinalVariableName" /> <!-- local, non-final variables, including catch parameters --> <module name="LocalVariableName" /> <!-- static, non-final fields --> <module name="StaticVariableName"> <property name="format" value="(^[A-Za-z0-9_]{0,32}$)" /> </module> <!-- packages --> <module name="PackageName"> <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$" /> </module> <!-- classes and interfaces --> <module name="TypeName"> <property name="format" value="(^[A-Z][a-zA-Z0-9]{0,31}$)" /> </module> <!-- methods --> <module name="MethodName"> <property name="format" value="(^[a-z][a-zA-Z0-9]{0,38}$)" /> </module> <!-- non-static fields --> <!-- 对应的接口已定 参数先不做修改 <module name="MemberName"> <property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,30}$)" /> </module> --> <module name="MemberName"> <property name="format" value="(^[a-z][a-zA-Z0-9]{0,31}$)" /> </module> <!-- parameters --> <module name="ParameterName"> <property name="format" value="(^[a-z][a-zA-Z0-9_]{0,31}$)" /> </module> <!-- constants (static, final fields) --> <module name="ConstantName"> <property name="format" value="(^[A-Z0-9_]{0,38}$)" /> </module> <!--option: 定义左大括号'{'显示位置,eol在同一行显示,nl在下一行显示 maxLineLength: 大括号'{'所在行行最多容纳的字符数 tokens: 该属性适用的类型,例:CLASS_DEF,INTERFACE_DEF,METHOD_DEF,CTOR_DEF --> <module name="LeftCurly"> <property name="option" value="eol" /> </module> <!-- Checks the placement of right curly braces ('}') for else, try, and catch tokens. The policy to verify is specified using property option. option: 右大括号是否单独一行显示 tokens: 定义检查的类型--> <module name="RightCurly"> <property name="option" value="alone" /> <property name="tokens" value="LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_FINALLY"/> <!-- <property name="tokens" value="LITERAL_ELSE,LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_FINALLY"/> --> </module> <!-- NeedBraces 检查是否应该使用括号的地方没有加括号 tokens: 定义检查的类型 --> <module name="NeedBraces" /> <!-- 代码缩进 --> <module name="Indentation" > <property name="arrayInitIndent" value="4"/> </module> <!-- 每一行只能定义一个变量 --> <module name="MultipleVariableDeclarations" /> <!-- Checks the style of array type definitions. Some like Java-style: public static void main(String[] args) and some like C-style: public static void main(String args[]) 检查再定义数组时,采用java风格还是c风格,例如:int[] num是java风格,int num[]是c风格。默认是java风格 --> <module name="ArrayTypeStyle" /> <!-- Checks that switch statement has "default" clause. 检查switch语句是否有‘default’从句 Rationale: It's usually a good idea to introduce a default case in every switch statement. Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch, e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type. --> <module name="MissingSwitchDefault" /> <!--检查switch中case后是否加入了跳出语句,例如:return、break、throw、continue --> <module name="FallThrough" /> <!--检查default是否在语句的最后 --> <module name="DefaultComesLast"> <property name="severity" value="warning"/> </module> <!-- ModifierOrder 检查修饰符的顺序,默认是 public,protected,private,abstract,static,final,transient,volatile,synchronized,native --> <module name="ModifierOrder" /> <!-- 每行字符数为150 --> <module name="LineLength"> <property name="max" value="150" /> </module> <!-- 不允许使用魔法数 <module name="MagicNumber" />--> <!-- 禁用Finalizers --> <module name="NoFinalizer" /> <!-- 每行一条语句 --> <module name="OneStatementPerLine" /> <!-- 检查是否跨越分支 在有跨越分支的case分支代码中添加“fallthru”、“fall through”、“fallthrough”、 “falls through”、“fallsthrough”等注释(区分大小写)时,便可抑制警告。--> <module name="FallThrough" /> <!-- 检查所有的重载放在一起 --> <module name="OverloadMethodsDeclarationOrder"/> <!-- 检查是否有多余的修饰符,例如:接口中的方法不必使用public、abstract修饰 --> <module name="RedundantModifier" /> <!-- 检查方法的javadoc的注释 scope: 可以检查的方法的范围,例如:public只能检查public修饰的方法,private可以检查所有的方法 allowMissingParamTags: 是否忽略对参数注释的检查 allowMissingThrowsTags: 是否忽略对throws注释的检查 allowMissingReturnTag: 是否忽略对return注释的检查 --> <module name="JavadocMethod"> <property name="scope" value="private" /> <property name="allowMissingParamTags" value="true" /> <property name="allowMissingThrowsTags" value="true" /> <property name="allowMissingReturnTag" value="true" /> <property name="tokens" value="METHOD_DEF" /> <property name="allowUndeclaredRTE" value="true" /> <property name="allowThrowsTagsForSubclasses" value="true" /> <!-- 允许get set 方法没有注释 --> <property name="allowMissingPropertyJavadoc" value="true" /> </module> <!-- 检查在重写了equals方法后是否重写了hashCode方法 --> <module name="EqualsHashCode" /> <!-- Checks for overly complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc. 检查boolean值是否冗余的地方 Rationale: Complex boolean logic makes code hard to understand and maintain. --> <module name="SimplifyBooleanExpression" /> <!-- Checks for overly complicated boolean return statements. For example the following code 检查是否存在过度复杂的boolean返回值 if (valid()) return false; else return true; could be written as return !valid(); The Idea for this Check has been shamelessly stolen from the equivalent PMD rule. --> <module name="SimplifyBooleanReturn" /> <!-- Checks that a class which has only private constructors is declared as final.只有私有构造器的类必须声明为final --> <module name="FinalClass" /> <!-- Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor. 确保Utils类(只提供static方法和属性的类)没有public构造器。 Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor. If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses: public class StringUtils // not final to allow subclassing { protected StringUtils() { throw new UnsupportedOperationException(); // prevents calls from subclass } public static int count(char c, String s) { // ... } } --> <module name="HideUtilityClassConstructor" /> <!-- Checks visibility of class members. Only static final members may be public; other class members must be private unless property protectedAllowed or packageAllowed is set. 检查class成员属性可见性。只有static final 修饰的成员是可以public的。其他的成员属性必需是private的,除非属性protectedAllowed或者packageAllowed设置了true. Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default). Note: Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow CMP for EJB 1.1 with the default settings. With EJB 2.0 it is not longer necessary to have public access for persistent fields, hence the default has been changed. Rationale: Enforce encapsulation. 强制封装 --> <module name="VisibilityModifier" /> <!-- Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification, Section 3.10.1. 检查是否在long类型是否定义了大写的L.字母小写l和数字1(一)很相似。 looks a lot like 1. --> <module name="UpperEll" /> <!-- Checks the number of parameters of a method or constructor. max default 7个. --> <module name="ParameterNumber" > <property name="max" value="8"/> </module> <!-- Checks for long methods and constructors. max default 150行. max=300 设置长度300 --> <module name="MethodLength"> <property name="max" value="300" /> </module> <!--- 字符串比较必须使用 equals() --> <module name="StringLiteralEquality"> </module> <!-- if-else嵌套语句个数 最多4层 --> <module name="NestedIfDepth"> <property name="max" value="4" /> </module> <!-- try-catch 嵌套语句个数 最多2层 --> <module name="NestedTryDepth"> <property name="max" value="2" /> </module> <!-- 返回个数 <module name="ReturnCount"> <property name="max" value="10" /> <property name="format" value="^$" /> </module>--> </module></module>
备注二
下载相关文件 https://github.com/checkstyle/checkstyle/releases/
xml https://checkstyle.sourceforge.io/
备注三
在源代码中可以使用快捷键将代码依照Google Java Style Guide进行格式化:
Ctrl + Alt + L 格式化代码
Ctrl + Alt + I 自动缩进
Ctrl + Alt + O 整理import
这篇关于IDEA使用CheckStyle代码规范的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!