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:
as methods that are differ from interface methods are rarely used, so in most cases user will benefit from checking for them.
validateAbstractClassNames - Control whether to validate abstract class names.
Type is boolean.
Default value is false.
illegalClassNames - Specify classes that should not be used
as types in variable declarations, return values or parameters.
Type is java.lang.String[].
Default value is HashMap, HashSet, LinkedHashMap, LinkedHashSet, TreeMap,
TreeSet, java.util.HashMap, java.util.HashSet, java.util.LinkedHashMap,
java.util.LinkedHashSet, java.util.TreeMap, java.util.TreeSet.
legalAbstractClassNames - Define abstract classes that may be used as types.
Type is java.lang.String[].
Default value is "".
ignoredMethodNames - Specify methods that should not be checked.
Type is java.lang.String[].
Default value is getEnvironment, getInitialContext.
illegalAbstractClassNameFormat - Specify RegExp for illegal abstract class
names.
Type is java.util.regex.Pattern.
Default value is "^(.*[.])?Abstract.*$".
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 is java.lang.String[].
Validation type is tokenTypesSet.
Default value is "".
tokens - tokens to check
Type is java.lang.String[].
Validation type is tokenSet.
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.
To configure the default check:
<module name="IllegalType"/>
public class Test extends TreeSet { // violation
public <T extends java.util.HashSet> void method() { // violation
LinkedHashMap<Integer, String> lhmap =
new LinkedHashMap<Integer, String>(); // violation
TreeMap<Integer, String> treemap =
new TreeMap<Integer, String>(); // violation
Test t; // OK
HashMap<String, String> hmap; // violation
Queue<Integer> intqueue; // OK
java.lang.IllegalArgumentException illegalex; // OK
java.util.TreeSet treeset; // violation
}
}
To configure the Check so that particular tokens are checked:
<module name="IllegalType"> <property name="tokens" value="METHOD_DEF"/> </module>
public class Test extends TreeSet { // OK
public <T extends java.util.HashSet> void method() { // violation
LinkedHashMap<Integer, String> lhmap =
new LinkedHashMap<Integer, String>(); // OK
java.lang.IllegalArgumentException illegalex; // OK
java.util.TreeSet treeset; // Ok
}
public <T extends java.util.HashSet> void typeParam(T t) {} // violation
public void fullName(TreeSet a) {} // OK
}
To configure the Check so that it ignores function() methods:
<module name="IllegalType"> <property name="ignoredMethodNames" value="function"/> </module>
public class Test {
public HashMap<String, String> function() { // OK
// code
}
public HashMap<String, String> function1() { // violation
// code
}
}
To configure the Check so that it validates abstract class names:
<module name="IllegalType">
<property name="validateAbstractClassNames" value="true"/>
<property name="illegalAbstractClassNameFormat" value="Gitt"/>
</module>
class Test extends Gitter { // violation
}
class Test1 extends Github { // OK
}
To configure the Check so that it verifies only public, protected or static methods and fields:
<module name="IllegalType">
<property name="memberModifiers" value="LITERAL_PUBLIC,
LITERAL_PROTECTED, LITERAL_STATIC"/>
</module>
public class Test {
public HashMap<String, String> function1() { // violation
// code
}
private HashMap<String, String> function2() { // OK
// code
}
protected HashMap<Integer, String> function3() { // violation
// code
}
public static TreeMap<Integer, String> function4() { // violation
// code
}
}
To configure the check so that it verifies usage of types Boolean and Foo:
<module name="IllegalType">
<property name="illegalClassNames" value="Boolean, Foo"/>
</module>
public class Test {
public Set<Boolean> set; // violation
public java.util.List<Map<Boolean, Foo>> list; // violation
private void method(List<Foo> list, Boolean value) { // violation
SomeType.<Boolean>foo(); // violation
final Consumer<Foo> consumer = Foo<Boolean>::foo; // violation
}
public <T extends Boolean, U extends Serializable> void typeParam(T a) {} // violation
public void fullName(java.util.ArrayList<? super Boolean> a) {} // violation
public abstract Set<Boolean> shortName(Set<? super Boolean> a); // violation
public Set<? extends Foo> typeArgument() { // violation
return new TreeSet<Foo<Boolean>>();
}
}
To configure the check to target fields types only:
<module name="IllegalType"> <property name="illegalClassNames" value="java.util.Optional"/> <property name="tokens" value="VARIABLE_DEF"/> <property name="id" value="IllegalTypeOptionalAsField"/> </module> <module name="SuppressionXpathSingleFilter"> <property name="query" value="//METHOD_DEF//*"/> <property name="id" value="IllegalTypeOptionalAsField"/> </module>
import java.util.Optional;
public class Main {
static int field1 = 4; // OK
public Optional<String> field2; // violation, usage of type 'Optional' is not allowed
protected String field3; // OK
Optional<String> field4; // violation, usage of type 'Optional' is not allowed
private Optional<String> field5; // violation, usage of type 'Optional' is not allowed
void foo() {
Optional<String> i; // OK
}
public <T extends java.util.Optional> void method(T t) { // OK
Optional<T> i; // OK
}
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
illegal.type
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private static java.lang.String[] |
DEFAULT_IGNORED_METHOD_NAMES
Default ignored method names.
|
private static java.lang.String[] |
DEFAULT_ILLEGAL_TYPES
Types illegal by default.
|
private java.util.Set<java.lang.String> |
ignoredMethodNames
Specify methods that should not be checked.
|
private java.util.regex.Pattern |
illegalAbstractClassNameFormat
Specify RegExp for illegal abstract class names.
|
private java.util.Set<java.lang.String> |
illegalClassNames
Specify classes that should not be used as types in variable declarations,
return values or parameters.
|
private java.util.Set<java.lang.String> |
illegalShortClassNames
Illegal short classes.
|
private java.util.Set<java.lang.String> |
legalAbstractClassNames
Define abstract classes that may be used as types.
|
private java.util.List<java.lang.Integer> |
memberModifiers
Control whether to check only methods and fields with any of the specified modifiers.
|
static java.lang.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 and Description |
|---|
IllegalTypeCheck()
Creates new instance of the check.
|
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(DetailAST rootAST)
Called before the starting to process a tree.
|
private void |
checkBaseTypes(DetailAST clause)
Checks the
extends or implements 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(java.lang.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 java.lang.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(java.lang.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(java.lang.String... methodNames)
Setter to specify methods that should not be checked.
|
void |
setIllegalAbstractClassNameFormat(java.util.regex.Pattern pattern)
Setter to specify RegExp for illegal abstract class names.
|
void |
setIllegalClassNames(java.lang.String... classNames)
Setter to specify classes that should not be used as types in variable declarations,
return values or parameters.
|
void |
setLegalAbstractClassNames(java.lang.String... classNames)
Setter to define abstract classes that may be used as types.
|
void |
setMemberModifiers(java.lang.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.
|
clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_KEY
private static final java.lang.String[] DEFAULT_ILLEGAL_TYPES
private static final java.lang.String[] DEFAULT_IGNORED_METHOD_NAMES
private final java.util.Set<java.lang.String> illegalClassNames
private final java.util.Set<java.lang.String> illegalShortClassNames
private final java.util.Set<java.lang.String> legalAbstractClassNames
private final java.util.Set<java.lang.String> ignoredMethodNames
private java.util.List<java.lang.Integer> memberModifiers
private java.util.regex.Pattern illegalAbstractClassNameFormat
private boolean validateAbstractClassNames
public IllegalTypeCheck()
public void setIllegalAbstractClassNameFormat(java.util.regex.Pattern pattern)
pattern - a pattern.public void setValidateAbstractClassNames(boolean validateAbstractClassNames)
validateAbstractClassNames - whether abstract class names must be ignored.public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic void beginTree(DetailAST rootAST)
AbstractCheckbeginTree in class AbstractCheckrootAST - the root of the treepublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processprivate boolean isVerifiable(DetailAST methodOrVariableDef)
methodOrVariableDef - METHOD_DEF or VARIABLE_DEF ast node.private boolean isContainVerifiableType(DetailAST modifiers)
modifiers - parent node for all modifiersprivate void visitTypeDef(DetailAST typeDef)
typeDef - class or interface for check.private void visitMethodDef(DetailAST methodDef)
methodDef - method for check.private void visitParameterDef(DetailAST parameterDef)
parameterDef - parameter list for check.private void visitVariableDef(DetailAST variableDef)
variableDef - variable to check.private void visitMethodCallOrRef(DetailAST methodCallOrRef)
methodCallOrRef - method call/reference to check.private void visitImport(DetailAST importAst)
importAst - Importprivate static boolean isStarImport(DetailAST importAst)
import java.util.*;
importAst - Importprivate void checkClassName(DetailAST ast)
ast - node to check.private void checkIdent(DetailAST type)
type - node to check.private void checkBaseTypes(DetailAST clause)
extends or implements statement.clause - DetailAST for either TokenTypes.EXTENDS_CLAUSE or
TokenTypes.IMPLEMENTS_CLAUSEprivate void checkType(DetailAST type)
type - node to check.private void checkTypeBounds(DetailAST type)
type - node to check.private void checkTypeParameters(DetailAST node)
node - node to check.private void checkTypeArguments(DetailAST node)
node - node to check.private boolean isMatchingClassName(java.lang.String className)
className - class name to check.private void extendIllegalClassNamesWithShortName(java.lang.String canonicalName)
canonicalName -
Canonical name of imported type.private static java.lang.String getImportedTypeCanonicalName(DetailAST importAst)
importAst - Importprivate static DetailAST getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst)
currentNodeAst - Current node in consideringsubTreeRootAst - SubTree rootprivate boolean isCheckedMethod(DetailAST ast)
ast - method def to check.public void setIllegalClassNames(java.lang.String... classNames)
classNames - array of illegal variable typespublic void setIgnoredMethodNames(java.lang.String... methodNames)
methodNames - array of ignored method namespublic void setLegalAbstractClassNames(java.lang.String... classNames)
classNames - array of legal abstract class namespublic void setMemberModifiers(java.lang.String modifiers)
modifiers - String contains modifiers.Copyright © 2001-2022. All Rights Reserved.