public class IllegalInstantiationCheck extends AbstractCheck
Checks for illegal instantiations where a factory method is preferred.
Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.
A simple example is the java.lang.Boolean class.
For performance reasons, it is preferable to use the predefined constants
TRUE and FALSE.
Constructor invocations should be replaced by calls to Boolean.valueOf().
Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools.
There is a limitation that it is currently not possible to specify array classes.
classes - Specify fully qualified class names that should not be instantiated.
Type is java.lang.String[].
Default value is "".
tokens - tokens to check
Type is java.lang.String[].
Validation type is tokenSet.
Default value is:
CLASS_DEF.
To configure the check:
<module name="IllegalInstantiation"/>
Example:
public class MyTest {
public class Boolean {
boolean a;
public Boolean (boolean a) { this.a = a; }
}
public void myTest (boolean a, int b) {
Boolean c = new Boolean(a); // OK
java.lang.Boolean d = new java.lang.Boolean(a); // OK
Integer e = new Integer(b); // OK
Integer f = Integer.valueOf(b); // OK
}
}
To configure the check to find instantiations of java.lang.Boolean
and java.lang.Integer. NOTE: Even if property tokens
is completely removed from the following configuration, Checkstyle will produce
the same results for violation. This is because if property tokens is not
defined in the configuration, Checkstyle will supply it with list of default tokens
CLASS_DEF, LITERAL_NEW, PACKAGE_DEF, IMPORT for this check. The property is
defined in this example only to provide clarity:
<module name="IllegalInstantiation">
<property name="classes" value="java.lang.Boolean,
java.lang.Integer"/>
<property name="tokens" value="CLASS_DEF, LITERAL_NEW,
PACKAGE_DEF, IMPORT"/>
</module>
Example:
public class MyTest {
public class Boolean {
boolean a;
public Boolean (boolean a) { this.a = a; }
}
public void myTest (boolean a, int b) {
Boolean c = new Boolean(a); // OK
java.lang.Boolean d = new java.lang.Boolean(a); // violation, instantiation of
// java.lang.Boolean should be avoided
Integer e = new Integer(b); // violation, instantiation of
// java.lang.Integer should be avoided
Integer f = Integer.valueOf(b); // OK
}
}
To configure the check to allow violations for local classes vs classes
defined in the check, for example java.lang.Boolean, property
tokens must be defined to not mention CLASS_DEF, so its
value should be LITERAL_NEW, PACKAGE_DEF, IMPORT:
<module name="IllegalInstantiation">
<property name="classes" value="java.lang.Boolean,
java.lang.Integer"/>
<property name="tokens" value="LITERAL_NEW, PACKAGE_DEF,
IMPORT"/>
</module>
Example:
public class MyTest {
public class Boolean {
boolean a;
public Boolean (boolean a) { this.a = a; }
}
public void myTest (boolean a, int b) {
Boolean c = new Boolean(a); // violation, instantiation of
// java.lang.Boolean should be avoided
java.lang.Boolean d = new java.lang.Boolean(a); // violation, instantiation of
// java.lang.Boolean should be avoided
Integer e = new Integer(b); // violation, instantiation of
// java.lang.Integer should be avoided
Integer f = Integer.valueOf(b); // OK
}
}
Finally, there is a limitation that it is currently not possible to specify array classes:
<module name="IllegalInstantiation">
<property name="classes" value="java.lang.Boolean[],
Boolean[], java.lang.Integer[], Integer[]"/>
</module>
Example:
public class MyTest {
public void myTest () {
Boolean[] newBoolArray = new Boolean[]{true,true,false}; // OK
Integer[] newIntArray = new Integer[]{1,2,3}; // OK
}
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
instantiation.avoid
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private java.util.Set<java.lang.String> |
classes
Specify fully qualified class names that should not be instantiated.
|
private java.util.Set<java.lang.String> |
classNames
The class names defined in the file.
|
private java.util.Set<FullIdent> |
imports
The imports for the file.
|
private java.util.Set<DetailAST> |
instantiations
The instantiations in the file.
|
private static java.lang.String |
JAVA_LANG
java.lang package as string. |
static java.lang.String |
MSG_KEY
A key is pointing to the warning message text in "messages.properties"
file.
|
private java.lang.String |
pkgName
Name of the package.
|
| Constructor and Description |
|---|
IllegalInstantiationCheck() |
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(DetailAST rootAST)
Called before the starting to process a tree.
|
private java.lang.String |
checkImportStatements(java.lang.String className)
Check import statements.
|
void |
finishTree(DetailAST rootAST)
Called after finished processing a tree.
|
int[] |
getAcceptableTokens()
The configurable token set.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
private java.lang.String |
getIllegalInstantiation(java.lang.String className)
Checks illegal instantiations.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private boolean |
isSamePackage(java.lang.String className,
int pkgNameLen,
java.lang.String illegal)
Check that type is of the same package.
|
private boolean |
isStandardClass(java.lang.String className,
java.lang.String illegal)
Is Standard Class.
|
private void |
postProcessLiteralNew(DetailAST newTokenAst)
Processes one of the collected "new" tokens when walking tree
has finished.
|
private void |
processClassDef(DetailAST ast)
Collects classes defined in the source file.
|
private void |
processImport(DetailAST ast)
Perform processing for an import token.
|
private void |
processLiteralNew(DetailAST ast)
Collects a "new" token.
|
private void |
processPackageDef(DetailAST ast)
Perform processing for an package token.
|
void |
setClasses(java.lang.String... names)
Setter to specify fully qualified class names that should not be instantiated.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
clearViolations, destroy, 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 JAVA_LANG
java.lang package as string.private final java.util.Set<java.lang.String> classNames
private final java.util.Set<DetailAST> instantiations
private java.util.Set<java.lang.String> classes
private java.lang.String pkgName
public IllegalInstantiationCheck()
public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void beginTree(DetailAST rootAST)
AbstractCheckbeginTree in class AbstractCheckrootAST - the root of the treepublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processpublic void finishTree(DetailAST rootAST)
AbstractCheckfinishTree in class AbstractCheckrootAST - the root of the treeprivate void processClassDef(DetailAST ast)
ast - the class def token.private void processImport(DetailAST ast)
ast - the import tokenprivate void processPackageDef(DetailAST ast)
ast - the package tokenprivate void processLiteralNew(DetailAST ast)
ast - the "new" tokenprivate void postProcessLiteralNew(DetailAST newTokenAst)
newTokenAst - the "new" token.private java.lang.String getIllegalInstantiation(java.lang.String className)
className - instantiated class, may or may not be qualifiedprivate java.lang.String checkImportStatements(java.lang.String className)
className - name of the classprivate boolean isSamePackage(java.lang.String className, int pkgNameLen, java.lang.String illegal)
className - class namepkgNameLen - package nameillegal - illegal valueprivate boolean isStandardClass(java.lang.String className, java.lang.String illegal)
className - class nameillegal - illegal valuepublic void setClasses(java.lang.String... names)
names - a comma separate list of class namesCopyright © 2001-2022. All Rights Reserved.