Class IllegalTypeCheck
- All Implemented Interfaces:
Configurable,Contextualizable
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
validateAbstractClassNames- Control whether to validate abstract class names. Type isboolean. Default value isfalse. -
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
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
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. Type isjava.lang.String[]. Validation type istokenTypesSet. Default value isno tokens. -
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.
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>>();
}
}
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.api.AutomaticBean
AutomaticBean.OutputStreamOptions -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidCalled before the starting to process a tree.int[]The configurable token set.int[]Returns the default token a check is interested in.int[]The tokens that this check must be registered for.voidsetIgnoredMethodNames(String... methodNames) Setter to specify methods that should not be checked.voidsetIllegalAbstractClassNameFormat(Pattern pattern) Setter to specify RegExp for illegal abstract class names.voidsetIllegalClassNames(String... classNames) Setter to specify classes that should not be used as types in variable declarations, return values or parameters.voidsetLegalAbstractClassNames(String... classNames) Setter to define abstract classes that may be used as types.voidsetMemberModifiers(String modifiers) Setter to control whether to check only methods and fields with any of the specified modifiers.voidsetValidateAbstractClassNames(boolean validateAbstractClassNames) Setter to control whether to validate abstract class names.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityMethods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
-
Constructor Details
-
IllegalTypeCheck
public IllegalTypeCheck()Creates new instance of the check.
-
-
Method Details
-
setIllegalAbstractClassNameFormat
Setter to specify RegExp for illegal abstract class names.- Parameters:
pattern- a pattern.
-
setValidateAbstractClassNames
public void setValidateAbstractClassNames(boolean validateAbstractClassNames) Setter to control whether to validate abstract class names.- Parameters:
validateAbstractClassNames- whether abstract class names must be ignored.
-
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:
-
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:
-
beginTree
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
-
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:
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
setIllegalClassNames
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
-
setIgnoredMethodNames
Setter to specify methods that should not be checked.- Parameters:
methodNames- array of ignored method names
-
setLegalAbstractClassNames
Setter to define abstract classes that may be used as types.- Parameters:
classNames- array of legal abstract class names
-
setMemberModifiers
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.- Parameters:
modifiers- String contains modifiers.
-