- Custom Rules in Checkstyle for ensuring Logger is declared as a Static Final Class Attribute
- package com.mystuff.checkstyle.hecks;
- import com.puppycrawl.tools.checkstyle.api.Check;
- import com.puppycrawl.tools.checkstyle.api.DetailAST;
- import com.puppycrawl.tools.checkstyle.api.FullIdent;
- import com.puppycrawl.tools.checkstyle.api.TokenTypes;
- import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
- /**
- *
- *
- * This package provides the custom checks that were required outside
- * of the standard checks provided
- *
- */
- public class LoggerAttrCheck extends Check
- {
- /**
- *
- *
- * The Logger must be declared as a static final class attribute
- *
- */
- @Override
- public int[] getDefaultTokens()
- {
- return new int[] { TokenTypes.VARIABLE_DEF};
- }
- @Override
- public void visitToken(DetailAST aAST)
- {
- if(aAST.getType()==TokenTypes.VARIABLE_DEF)
- visitVariableDef(aAST);
- }
- /**
- * Checks type of given variable.
- * @param aAST variable to check.
- */
- private void visitVariableDef(DetailAST aAST)
- {
- checkVariableDefn(aAST);
- }
- /**
- *
- * Checks variable to see if its a Logger and static final
- * * @param aAST node to check.
- */
- private void checkVariableDefn(DetailAST aAST)
- {
- final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE);
- final FullIdent ident = CheckUtils.createFullType(type);
- if ((ident.getText().equals("Logger")))
- {
- if((!aAST.branchContains(TokenTypes.FINAL))||(!aAST.branchContainsTokenTypes.LITERAL_STATIC)))
- {
- log(type.getLineNo(), type.getColumnNo(),
- "Logger not defined as static final class attribute", type.getText());
- }
- }
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE checkstyle-packages PUBLIC
- "-//Puppy Crawl//DTD Package Names 1.3//EN"
- "http://www.puppycrawl.com/dtds/packages_1_3.dtd">
- <checkstyle-packages>
- <package name="com.mystuff.checkstyle.checks"/>
- </checkstyle-packages>