Class EqualsAvoidNullCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck
-
- All Implemented Interfaces:
Configurable,Contextualizable
public class EqualsAvoidNullCheck extends AbstractCheck
Checks that any combination of String literals is on the left side of an
equals()comparison. Also checks for String literals assigned to some field (such assomeString.equals(anotherString = "text")).Rationale: Calling the
equals()method on String literals will avoid a potentialNullPointerException. Also, it is pretty common to see null checks right before equals comparisons but following this rule such checks are not required.-
Property
ignoreEqualsIgnoreCase- Control whether to ignoreString.equalsIgnoreCase(String)invocations. Type isboolean. Default value isfalse.
To configure the check:
<module name="EqualsAvoidNull"/>
Example:
String nullString = null; nullString.equals("My_Sweet_String"); // violation "My_Sweet_String".equals(nullString); // OK nullString.equalsIgnoreCase("My_Sweet_String"); // violation "My_Sweet_String".equalsIgnoreCase(nullString); // OKTo configure the check to allow ignoreEqualsIgnoreCase:
<module name="EqualsAvoidNull"> <property name="ignoreEqualsIgnoreCase" value="true"/> </module>
Example:
String nullString = null; nullString.equals("My_Sweet_String"); // violation "My_Sweet_String".equals(nullString); // OK nullString.equalsIgnoreCase("My_Sweet_String"); // OK "My_Sweet_String".equalsIgnoreCase(nullString); // OKParent is
com.puppycrawl.tools.checkstyle.TreeWalkerViolation Message Keys:
-
equals.avoid.null -
equalsIgnoreCase.avoid.null
- Since:
- 5.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classEqualsAvoidNullCheck.FieldFrameHolds the names of fields of a type.-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private EqualsAvoidNullCheck.FieldFramecurrentFrameStack of sets of field names, one for each class of a set of nested classes.private static java.lang.StringEQUALSMethod name for comparison.private booleanignoreEqualsIgnoreCaseControl whether to ignoreString.equalsIgnoreCase(String)invocations.private static java.lang.StringLEFT_CURLYCurly for comparison.static java.lang.StringMSG_EQUALS_AVOID_NULLA key is pointing to the warning message text in "messages.properties" file.static java.lang.StringMSG_EQUALS_IGNORE_CASE_AVOID_NULLA key is pointing to the warning message text in "messages.properties" file.private static java.lang.StringSTRINGType name for comparison.
-
Constructor Summary
Constructors Constructor Description EqualsAvoidNullCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private static booleanastTypeIsClassOrEnumOrRecordDef(int tokenType)Verify that a token is either CLASS_DEF, RECORD_DEF, or ENUM_DEF.voidbeginTree(DetailAST rootAST)Called before the starting to process a tree.private voidcheckMethodCall(DetailAST methodCall)Check whether the method call should be violated.private static booleancontainsAllSafeTokens(DetailAST expr)Looks for all "safe" Token combinations in the argument expression branch.private static booleancontainsOneArgument(DetailAST methodCall)Verify that method call has one argument.voidfinishTree(DetailAST ast)Called after finished processing a tree.int[]getAcceptableTokens()The configurable token set.int[]getDefaultTokens()Returns the default token a check is interested in.private static java.lang.StringgetFieldType(DetailAST field)Get field type.private static EqualsAvoidNullCheck.FieldFramegetObjectFrame(EqualsAvoidNullCheck.FieldFrame frame)Get the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.int[]getRequiredTokens()The tokens that this check must be registered for.private booleanisCalledOnStringFieldOrVariable(DetailAST objCalledOn)Determine, whether equals method is called on a field of String type.private booleanisStringFieldOrVariable(DetailAST objCalledOn)Whether the field or the variable is of String type.private booleanisStringFieldOrVariableFromClass(DetailAST objCalledOn, java.lang.String className)Whether the field or the variable from the specified class is of String type.private booleanisStringFieldOrVariableFromThisInstance(DetailAST objCalledOn)Whether the field or the variable from THIS instance is of String type.private voidleaveLiteralNew(DetailAST ast)Determine whether LITERAL_NEW is an anonymous class definition and leave the frame it is in.private voidleaveSlist(DetailAST ast)Determine whether SLIST begins a block, determined by braces.voidleaveToken(DetailAST ast)Called after all the child nodes have been process.private voidprocessFrame(DetailAST ast)Process CLASS_DEF, METHOD_DEF, LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, LITERAL_CATCH, LITERAL_TRY, CTOR_DEF, ENUM_DEF, ENUM_CONSTANT_DEF.private voidprocessLiteralNew(DetailAST ast)Determine whether LITERAL_NEW is an anonymous class definition and add it as a frame in this case.private voidprocessMethodCall(DetailAST methodCall)Add the method call to the current frame if it should be processed.private voidprocessSlist(DetailAST ast)Determine whether SLIST begins a block, determined by braces, and add it as a frame in this case.voidsetIgnoreEqualsIgnoreCase(boolean newValue)Setter to control whether to ignoreString.equalsIgnoreCase(String)invocations.private static DetailASTskipVariableAssign(DetailAST currentAST)Skips over an inner assign portion of an argument expression.private voidtraverseFieldFrameTree(EqualsAvoidNullCheck.FieldFrame frame)Traverse the tree of the field frames to check all equals method calls.voidvisitToken(DetailAST ast)Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_EQUALS_AVOID_NULL
public static final java.lang.String MSG_EQUALS_AVOID_NULL
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_EQUALS_IGNORE_CASE_AVOID_NULL
public static final java.lang.String MSG_EQUALS_IGNORE_CASE_AVOID_NULL
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
EQUALS
private static final java.lang.String EQUALS
Method name for comparison.- See Also:
- Constant Field Values
-
STRING
private static final java.lang.String STRING
Type name for comparison.- See Also:
- Constant Field Values
-
LEFT_CURLY
private static final java.lang.String LEFT_CURLY
Curly for comparison.- See Also:
- Constant Field Values
-
ignoreEqualsIgnoreCase
private boolean ignoreEqualsIgnoreCase
Control whether to ignoreString.equalsIgnoreCase(String)invocations.
-
currentFrame
private EqualsAvoidNullCheck.FieldFrame currentFrame
Stack of sets of field names, one for each class of a set of nested classes.
-
-
Constructor Detail
-
EqualsAvoidNullCheck
public EqualsAvoidNullCheck()
-
-
Method Detail
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheckReturns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokensin classAbstractCheck- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheckThe configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokensin classAbstractCheck- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Specified by:
getRequiredTokensin classAbstractCheck- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
setIgnoreEqualsIgnoreCase
public void setIgnoreEqualsIgnoreCase(boolean newValue)
Setter to control whether to ignoreString.equalsIgnoreCase(String)invocations.- Parameters:
newValue- whether to ignore checkingString.equalsIgnoreCase(String).
-
beginTree
public void beginTree(DetailAST rootAST)
Description copied from class:AbstractCheckCalled before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTreein classAbstractCheck- Parameters:
rootAST- the root of the tree
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
leaveToken
public void leaveToken(DetailAST ast)
Description copied from class:AbstractCheckCalled after all the child nodes have been process.- Overrides:
leaveTokenin classAbstractCheck- Parameters:
ast- the token leaving
-
finishTree
public void finishTree(DetailAST ast)
Description copied from class:AbstractCheckCalled after finished processing a tree. Ideal place to report on information collected whilst processing a tree.- Overrides:
finishTreein classAbstractCheck- Parameters:
ast- the root of the tree
-
processSlist
private void processSlist(DetailAST ast)
Determine whether SLIST begins a block, determined by braces, and add it as a frame in this case.- Parameters:
ast- SLIST ast.
-
leaveSlist
private void leaveSlist(DetailAST ast)
Determine whether SLIST begins a block, determined by braces.- Parameters:
ast- SLIST ast.
-
processFrame
private void processFrame(DetailAST ast)
Process CLASS_DEF, METHOD_DEF, LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, LITERAL_CATCH, LITERAL_TRY, CTOR_DEF, ENUM_DEF, ENUM_CONSTANT_DEF.- Parameters:
ast- processed ast.
-
processMethodCall
private void processMethodCall(DetailAST methodCall)
Add the method call to the current frame if it should be processed.- Parameters:
methodCall- METHOD_CALL ast.
-
processLiteralNew
private void processLiteralNew(DetailAST ast)
Determine whether LITERAL_NEW is an anonymous class definition and add it as a frame in this case.- Parameters:
ast- LITERAL_NEW ast.
-
leaveLiteralNew
private void leaveLiteralNew(DetailAST ast)
Determine whether LITERAL_NEW is an anonymous class definition and leave the frame it is in.- Parameters:
ast- LITERAL_NEW ast.
-
traverseFieldFrameTree
private void traverseFieldFrameTree(EqualsAvoidNullCheck.FieldFrame frame)
Traverse the tree of the field frames to check all equals method calls.- Parameters:
frame- to check method calls in.
-
checkMethodCall
private void checkMethodCall(DetailAST methodCall)
Check whether the method call should be violated.- Parameters:
methodCall- method call to check.
-
containsOneArgument
private static boolean containsOneArgument(DetailAST methodCall)
Verify that method call has one argument.- Parameters:
methodCall- METHOD_CALL DetailAST- Returns:
- true if method call has one argument.
-
containsAllSafeTokens
private static boolean containsAllSafeTokens(DetailAST expr)
Looks for all "safe" Token combinations in the argument expression branch.- Parameters:
expr- the argument expression- Returns:
- - true if any child matches the set of tokens, false if not
-
skipVariableAssign
private static DetailAST skipVariableAssign(DetailAST currentAST)
Skips over an inner assign portion of an argument expression.- Parameters:
currentAST- current token in the argument expression- Returns:
- the next relevant token
-
isCalledOnStringFieldOrVariable
private boolean isCalledOnStringFieldOrVariable(DetailAST objCalledOn)
Determine, whether equals method is called on a field of String type.- Parameters:
objCalledOn- object ast.- Returns:
- true if the object is of String type.
-
isStringFieldOrVariable
private boolean isStringFieldOrVariable(DetailAST objCalledOn)
Whether the field or the variable is of String type.- Parameters:
objCalledOn- the field or the variable to check.- Returns:
- true if the field or the variable is of String type.
-
isStringFieldOrVariableFromThisInstance
private boolean isStringFieldOrVariableFromThisInstance(DetailAST objCalledOn)
Whether the field or the variable from THIS instance is of String type.- Parameters:
objCalledOn- the field or the variable from THIS instance to check.- Returns:
- true if the field or the variable from THIS instance is of String type.
-
isStringFieldOrVariableFromClass
private boolean isStringFieldOrVariableFromClass(DetailAST objCalledOn, java.lang.String className)
Whether the field or the variable from the specified class is of String type.- Parameters:
objCalledOn- the field or the variable from the specified class to check.className- the name of the class to check in.- Returns:
- true if the field or the variable from the specified class is of String type.
-
getObjectFrame
private static EqualsAvoidNullCheck.FieldFrame getObjectFrame(EqualsAvoidNullCheck.FieldFrame frame)
Get the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.- Parameters:
frame- to start the search from.- Returns:
- the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.
-
getFieldType
private static java.lang.String getFieldType(DetailAST field)
Get field type.- Parameters:
field- to get the type from.- Returns:
- type of the field.
-
astTypeIsClassOrEnumOrRecordDef
private static boolean astTypeIsClassOrEnumOrRecordDef(int tokenType)
Verify that a token is either CLASS_DEF, RECORD_DEF, or ENUM_DEF.- Parameters:
tokenType- the type of token- Returns:
- true if token is of specified type.
-
-