public class HideUtilityClassConstructorCheck extends AbstractCheck
Makes sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.
Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.
If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:
public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
public static int count(char c, String s) {
// ...
}
}
To configure the check:
<module name="HideUtilityClassConstructor"/>
Example:
class Test { // violation, class only has a static method and a constructor
public Test() {
}
public static void fun() {
}
}
class Foo { // OK
private Foo() {
}
static int n;
}
class Bar { // OK
protected Bar() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
}
class UtilityClass { // violation, class only has a static field
static float f;
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
hide.utility.class
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
static String |
MSG_KEY
A key is pointing to the warning message text in "messages.properties"
file.
|
| Constructor and Description |
|---|
HideUtilityClassConstructorCheck() |
| Modifier and Type | Method and Description |
|---|---|
int[] |
getAcceptableTokens()
The configurable token set.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
beginTree, clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final String MSG_KEY
public HideUtilityClassConstructorCheck()
public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processCopyright © 2001–2020. All rights reserved.