Class IllegalTypeCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public final class IllegalTypeCheck extends AbstractCheck
Checks that particular classes or interfaces are never used.Rationale: Helps reduce coupling on concrete classes.
For additional restriction of type usage see also: IllegalInstantiation, IllegalImport
It is possible to set illegal class names via short or canonical name. Specifying illegal type invokes analyzing imports and Check puts violations at corresponding declarations (of variables, methods or parameters). This helps to avoid ambiguous cases, e.g.:
java.awt.List
was set as illegal class name, then, code like:import java.util.List; ... List list; //No violation here
will be ok.
In most cases it's justified to put following classes to illegalClassNames:
- GregorianCalendar
- Hashtable
- ArrayList
- LinkedList
- Vector
as methods that are differ from interface methods are rarely used, so in most cases user will benefit from checking for them.
-
Property
ignoredMethodNames
- Specify methods that should not be checked. Type isjava.lang.String[]
. Default value isgetEnvironment, getInitialContext
. -
Property
illegalAbstractClassNameFormat
- Specify RegExp for illegal abstract class names. Type isjava.util.regex.Pattern
. Default value is"^(.*[.])?Abstract.*$"
. -
Property
illegalClassNames
- Specify classes that should not be used as types in variable declarations, return values or parameters. Type isjava.lang.String[]
. Default value isHashMap, HashSet, LinkedHashMap, LinkedHashSet, TreeMap, TreeSet, java.util.HashMap, java.util.HashSet, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.TreeMap, java.util.TreeSet
. -
Property
legalAbstractClassNames
- Define abstract classes that may be used as types. Type isjava.lang.String[]
. Default value is""
. -
Property
memberModifiers
- Control whether to check only methods and fields with any of the specified modifiers. This property does not affect method calls nor method references nor record components. Type isjava.lang.String[]
. Validation type istokenTypesSet
. Default value is""
. -
Property
validateAbstractClassNames
- Control whether to validate abstract class names. Type isboolean
. Default value isfalse
. -
Property
tokens
- tokens to check Type isjava.lang.String[]
. Validation type istokenSet
. Default value is: ANNOTATION_FIELD_DEF, CLASS_DEF, INTERFACE_DEF, METHOD_CALL, METHOD_DEF, METHOD_REF, PARAMETER_DEF, VARIABLE_DEF, PATTERN_VARIABLE_DEF, RECORD_DEF, RECORD_COMPONENT_DEF, RECORD_PATTERN_DEF.
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
illegal.type
- Since:
- 3.2
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private static String[]
DEFAULT_IGNORED_METHOD_NAMES
Default ignored method names.private static String[]
DEFAULT_ILLEGAL_TYPES
Types illegal by default.private Set<String>
ignoredMethodNames
Specify methods that should not be checked.private Pattern
illegalAbstractClassNameFormat
Specify RegExp for illegal abstract class names.private Set<String>
illegalClassNames
Specify classes that should not be used as types in variable declarations, return values or parameters.private Set<String>
illegalShortClassNames
Illegal short classes.private Set<String>
legalAbstractClassNames
Define abstract classes that may be used as types.private BitSet
memberModifiers
Control whether to check only methods and fields with any of the specified modifiers.static String
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.private boolean
validateAbstractClassNames
Control whether to validate abstract class names.
-
Constructor Summary
Constructors Constructor Description IllegalTypeCheck()
Creates new instance of the check.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
beginTree(DetailAST rootAST)
Called before the starting to process a tree.private void
checkBaseTypes(DetailAST clause)
Checks theextends
orimplements
statement.private void
checkClassName(DetailAST ast)
Checks type and type arguments/parameters of given method, parameter, variable or method call/reference.private void
checkIdent(DetailAST type)
Checks the identifier of the given type.private void
checkType(DetailAST type)
Checks the given type, its arguments and parameters.private void
checkTypeArguments(DetailAST node)
Checks the type arguments of the node.private void
checkTypeBounds(DetailAST type)
Checks the upper and lower bounds for the given type.private void
checkTypeParameters(DetailAST node)
Checks the type parameters of the node.private void
extendIllegalClassNamesWithShortName(String canonicalName)
Extends illegal class names set via imported short type name.int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.private static String
getImportedTypeCanonicalName(DetailAST importAst)
Gets imported type's canonical name.private static DetailAST
getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst)
Gets the next node of a syntactical tree (child of a current node or sibling of a current node, or sibling of a parent of a current node).int[]
getRequiredTokens()
The tokens that this check must be registered for.private boolean
isCheckedMethod(DetailAST ast)
Returns true if method has to be checked or false.private boolean
isContainVerifiableType(DetailAST modifiers)
Checks is modifiers contain verifiable type.private boolean
isMatchingClassName(String className)
Returns true if given class name is one of illegal classes or else false.private static boolean
isStarImport(DetailAST importAst)
Checks if current import is star import.private boolean
isVerifiable(DetailAST methodOrVariableDef)
Checks if current method's return type or variable's type is verifiable according to memberModifiers option.void
setIgnoredMethodNames(String... methodNames)
Setter to specify methods that should not be checked.void
setIllegalAbstractClassNameFormat(Pattern pattern)
Setter to specify RegExp for illegal abstract class names.void
setIllegalClassNames(String... classNames)
Setter to specify classes that should not be used as types in variable declarations, return values or parameters.void
setLegalAbstractClassNames(String... classNames)
Setter to define abstract classes that may be used as types.void
setMemberModifiers(String modifiers)
Setter to control whether to check only methods and fields with any of the specified modifiers.void
setValidateAbstractClassNames(boolean validateAbstractClassNames)
Setter to control whether to validate abstract class names.private void
visitImport(DetailAST importAst)
Checks imported type (as static and star imports are not supported by Check, only type is in the consideration).
If this type is illegal due to Check's options - puts violation on it.private void
visitMethodCallOrRef(DetailAST methodCallOrRef)
Checks the type arguments of given method call/reference.private void
visitMethodDef(DetailAST methodDef)
Checks return type of a given method.private void
visitParameterDef(DetailAST parameterDef)
Checks type of parameters.void
visitToken(DetailAST ast)
Called to process a token.private void
visitTypeDef(DetailAST typeDef)
Checks the super type and implemented interfaces of a given type.private void
visitVariableDef(DetailAST variableDef)
Checks type of given variable.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, 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.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY
public static final String MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
DEFAULT_ILLEGAL_TYPES
private static final String[] DEFAULT_ILLEGAL_TYPES
Types illegal by default.
-
DEFAULT_IGNORED_METHOD_NAMES
private static final String[] DEFAULT_IGNORED_METHOD_NAMES
Default ignored method names.
-
illegalClassNames
private final Set<String> illegalClassNames
Specify classes that should not be used as types in variable declarations, return values or parameters.
-
illegalShortClassNames
private final Set<String> illegalShortClassNames
Illegal short classes.
-
legalAbstractClassNames
private final Set<String> legalAbstractClassNames
Define abstract classes that may be used as types.
-
ignoredMethodNames
private final Set<String> ignoredMethodNames
Specify methods that should not be checked.
-
memberModifiers
private BitSet memberModifiers
Control whether to check only methods and fields with any of the specified modifiers. This property does not affect method calls nor method references nor record components.
-
illegalAbstractClassNameFormat
private Pattern illegalAbstractClassNameFormat
Specify RegExp for illegal abstract class names.
-
validateAbstractClassNames
private boolean validateAbstractClassNames
Control whether to validate abstract class names.
-
-
Constructor Detail
-
IllegalTypeCheck
public IllegalTypeCheck()
Creates new instance of the check.
-
-
Method Detail
-
setIllegalAbstractClassNameFormat
public void setIllegalAbstractClassNameFormat(Pattern pattern)
Setter to specify RegExp for illegal abstract class names.- Parameters:
pattern
- a pattern.- Since:
- 3.2
-
setValidateAbstractClassNames
public void setValidateAbstractClassNames(boolean validateAbstractClassNames)
Setter to control whether to validate abstract class names.- Parameters:
validateAbstractClassNames
- whether abstract class names must be ignored.- Since:
- 6.10
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheck
The 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:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
beginTree
public void beginTree(DetailAST rootAST)
Description copied from class:AbstractCheck
Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTree
in classAbstractCheck
- Parameters:
rootAST
- the root of the tree
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
isVerifiable
private boolean isVerifiable(DetailAST methodOrVariableDef)
Checks if current method's return type or variable's type is verifiable according to memberModifiers option.- Parameters:
methodOrVariableDef
- METHOD_DEF or VARIABLE_DEF ast node.- Returns:
- true if member is verifiable according to memberModifiers option.
-
isContainVerifiableType
private boolean isContainVerifiableType(DetailAST modifiers)
Checks is modifiers contain verifiable type.- Parameters:
modifiers
- parent node for all modifiers- Returns:
- true if method or variable can be verified
-
visitTypeDef
private void visitTypeDef(DetailAST typeDef)
Checks the super type and implemented interfaces of a given type.- Parameters:
typeDef
- class or interface for check.
-
visitMethodDef
private void visitMethodDef(DetailAST methodDef)
Checks return type of a given method.- Parameters:
methodDef
- method for check.
-
visitParameterDef
private void visitParameterDef(DetailAST parameterDef)
Checks type of parameters.- Parameters:
parameterDef
- parameter list for check.
-
visitVariableDef
private void visitVariableDef(DetailAST variableDef)
Checks type of given variable.- Parameters:
variableDef
- variable to check.
-
visitMethodCallOrRef
private void visitMethodCallOrRef(DetailAST methodCallOrRef)
Checks the type arguments of given method call/reference.- Parameters:
methodCallOrRef
- method call/reference to check.
-
visitImport
private void visitImport(DetailAST importAst)
Checks imported type (as static and star imports are not supported by Check, only type is in the consideration).
If this type is illegal due to Check's options - puts violation on it.- Parameters:
importAst
-Import
-
isStarImport
private static boolean isStarImport(DetailAST importAst)
Checks if current import is star import. E.g.:import java.util.*;
- Parameters:
importAst
-Import
- Returns:
- true if it is star import
-
checkClassName
private void checkClassName(DetailAST ast)
Checks type and type arguments/parameters of given method, parameter, variable or method call/reference.- Parameters:
ast
- node to check.
-
checkIdent
private void checkIdent(DetailAST type)
Checks the identifier of the given type.- Parameters:
type
- node to check.
-
checkBaseTypes
private void checkBaseTypes(DetailAST clause)
Checks theextends
orimplements
statement.- Parameters:
clause
- DetailAST for eitherTokenTypes.EXTENDS_CLAUSE
orTokenTypes.IMPLEMENTS_CLAUSE
-
checkType
private void checkType(DetailAST type)
Checks the given type, its arguments and parameters.- Parameters:
type
- node to check.
-
checkTypeBounds
private void checkTypeBounds(DetailAST type)
Checks the upper and lower bounds for the given type.- Parameters:
type
- node to check.
-
checkTypeParameters
private void checkTypeParameters(DetailAST node)
Checks the type parameters of the node.- Parameters:
node
- node to check.
-
checkTypeArguments
private void checkTypeArguments(DetailAST node)
Checks the type arguments of the node.- Parameters:
node
- node to check.
-
isMatchingClassName
private boolean isMatchingClassName(String className)
Returns true if given class name is one of illegal classes or else false.- Parameters:
className
- class name to check.- Returns:
- true if given class name is one of illegal classes or if it matches to abstract class names pattern.
-
extendIllegalClassNamesWithShortName
private void extendIllegalClassNamesWithShortName(String canonicalName)
Extends illegal class names set via imported short type name.- Parameters:
canonicalName
- Canonical name of imported type.
-
getImportedTypeCanonicalName
private static String getImportedTypeCanonicalName(DetailAST importAst)
Gets imported type's canonical name.- Parameters:
importAst
-Import
- Returns:
- Imported canonical type's name.
-
getNextSubTreeNode
private static DetailAST getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst)
Gets the next node of a syntactical tree (child of a current node or sibling of a current node, or sibling of a parent of a current node).- Parameters:
currentNodeAst
- Current node in consideringsubTreeRootAst
- SubTree root- Returns:
- Current node after bypassing, if current node reached the root of a subtree method returns null
-
isCheckedMethod
private boolean isCheckedMethod(DetailAST ast)
Returns true if method has to be checked or false.- Parameters:
ast
- method def to check.- Returns:
- true if we should check this method.
-
setIllegalClassNames
public void setIllegalClassNames(String... classNames)
Setter to specify classes that should not be used as types in variable declarations, return values or parameters.- Parameters:
classNames
- array of illegal variable types- Since:
- 3.2
-
setIgnoredMethodNames
public void setIgnoredMethodNames(String... methodNames)
Setter to specify methods that should not be checked.- Parameters:
methodNames
- array of ignored method names- Since:
- 3.2
-
setLegalAbstractClassNames
public void setLegalAbstractClassNames(String... classNames)
Setter to define abstract classes that may be used as types.- Parameters:
classNames
- array of legal abstract class names- Since:
- 4.2
-
setMemberModifiers
public void setMemberModifiers(String modifiers)
Setter to control whether to check only methods and fields with any of the specified modifiers. This property does not affect method calls nor method references nor record components.- Parameters:
modifiers
- String contains modifiers.- Since:
- 6.3
-
-