Since Checkstyle 3.0
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.
name | description | type | default value | since |
---|---|---|---|---|
classes | Specify fully qualified class names that should not be instantiated. | String[] | {} |
3.0 |
To configure the check:
<module name="Checker"> <module name="TreeWalker"> <module name="IllegalInstantiation"/> </module> </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); // 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
:
<module name="Checker"> <module name="TreeWalker"> <module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean, java.lang.Integer"/> </module> </module> </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 } }
Finally, there is a limitation that it is currently not possible to specify array classes:
<module name="Checker"> <module name="TreeWalker"> <module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean[], Boolean[], java.lang.Integer[], Integer[]"/> </module> </module> </module>
Example:
public class MyTest { public void myTest () { Boolean[] newBoolArray = new Boolean[]{true,true,false}; // OK Integer[] newIntArray = new Integer[]{1,2,3}; // OK } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.coding