Class RedundantModifierCheck
- All Implemented Interfaces:
Configurable,Contextualizable
Rationale: The Java Language Specification strongly discourages the usage
of public and abstract for method declarations in interface
definitions as a matter of style.
The check validates:
- Interface and annotation definitions.
- Final modifier on methods of final and anonymous classes.
-
Type declarations nested under interfaces that are declared as
publicorstatic. - Class constructors.
-
Nested
enumdefinitions that are declared asstatic. -
recorddefinitions that are declared asfinaland nestedrecorddefinitions that are declared asstatic. -
strictfpmodifier when using JDK 17 or later. See reason at JEP 306 -
finalmodifier on unnamed variables when using JDK 22 or later.
interfaces by definition are abstract so the abstract modifier is redundant on them.
Type declarations nested under interfaces by definition are public and static,
so the public and static modifiers on nested type declarations are redundant.
On the other hand, classes inside of interfaces can be abstract or non abstract.
So, abstract modifier is allowed.
Fields in interfaces and annotations are automatically public, static and final, so these modifiers are redundant as well.
As annotations are a form of interface, their fields are also automatically public, static and final just as their annotation fields are automatically public and abstract.
A record class is implicitly final and cannot be abstract, these restrictions emphasize that the API of a record class is defined solely by its state description, and cannot be enhanced later by another class. Nested records are implicitly static. This avoids an immediately enclosing instance which would silently add state to the record class. See JEP 395 for more info.
Enums by definition are static implicit subclasses of java.lang.Enum<E>.
So, the static modifier on the enums is redundant. In addition,
if enum is inside of interface, public modifier is also redundant.
Enums can also contain abstract methods and methods which can be overridden by the declared enumeration fields. See the following example:
public enum EnumClass {
FIELD_1,
FIELD_2 {
@Override
public final void method1() {} // violation expected
};
public void method1() {}
public final void method2() {} // no violation expected
}
Since these methods can be overridden in these situations, the final methods are not marked as redundant even though they can't be extended by other classes/enums.
Nested enum types are always static by default.
Final classes by definition cannot be extended so the final
modifier on the method of a final class is redundant.
Public modifier for constructors in non-public non-protected classes is always obsolete:
public class PublicClass {
public PublicClass() {} // OK
}
class PackagePrivateClass {
public PackagePrivateClass() {} // violation expected
}
There is no violation in the following example, because removing public modifier from ProtectedInnerClass constructor will make this code not compiling:
package a;
public class ClassExample {
protected class ProtectedInnerClass {
public ProtectedInnerClass () {}
}
}
package b;
import a.ClassExample;
public class ClassExtending extends ClassExample {
ProtectedInnerClass pc = new ProtectedInnerClass();
}
-
Property
jdkVersion- Set the JDK version that you are using. Old JDK version numbering is supported (e.g. 1.8 for Java 8) as well as just the major JDK version alone (e.g. 8) is supported. This property only considers features from officially released Java versions as supported. Features introduced in preview releases are not considered supported until they are included in a non-preview release. Type isjava.lang.String. Default value is"22". -
Property
tokens- tokens to check Type isjava.lang.String[]. Validation type istokenSet. Default value is: METHOD_DEF, VARIABLE_DEF, ANNOTATION_FIELD_DEF, INTERFACE_DEF, CTOR_DEF, CLASS_DEF, ENUM_DEF, RESOURCE, ANNOTATION_DEF, RECORD_DEF, PATTERN_VARIABLE_DEF, LITERAL_CATCH, LAMBDA.
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
redundantModifier
- Since:
- 3.0
-
Nested Class Summary
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final intConstant for jdk 17 version number.private static final intConstant for jdk 22 version number.private intSet the JDK version that you are using.static final StringA key is pointing to the warning message text in "messages.properties" file.private static final int[]An array of tokens for interface modifiers. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate voidcheckClassConstructorModifiers(DetailAST classCtorAst) Check if class constructor has proper modifiers.private voidcheckConstructorModifiers(DetailAST ctorDefAst) Check modifiers of constructor.private voidCheck if enum constructor has proper modifiers.private voidcheckForRedundantModifier(DetailAST ast, int... modifierTypes) Checks if given ast has a redundant modifier.private voidChecks if interface has proper modifiers.private voidCheck if the variable is unnamed and has redundant final modifier.int[]The configurable token set.int[]Returns the default token a check is interested in.getMethodAnnotationsList(DetailAST methodDef) Gets the list of annotations on method definition.int[]The tokens that this check must be registered for.private static booleanisAnnotatedWithSafeVarargs(DetailAST methodDef) Checks if method definition is annotated with.private static booleanisClassProtected(DetailAST classDef) Checks if given class ast has protected modifier.private static booleanisClassPublic(DetailAST ast) Checks if given class is accessible from "public" scope.private static booleanisEnumMember(DetailAST ast) Checks if current AST node is member of Enum.private static booleanChecks if current AST node is member of Interface or Annotation, not of their subnodes.private static booleanCheck if the variable is unnamed.private voidProcess validation of parameters for Methods with no definition.private voidDo validation of interface of annotation.private voidprocessLambdaParameters(DetailAST lambdaAst) Process lambda parameters.private voidprocessMethods(DetailAST ast) Process validation of Methods.private voidChecks if given resource has redundant modifiers.voidsetJdkVersion(String jdkVersion) Setter to set the JDK version that you are using.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, 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.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
TOKENS_FOR_INTERFACE_MODIFIERS
An array of tokens for interface modifiers. -
JDK_22
Constant for jdk 22 version number.- See Also:
-
JDK_17
Constant for jdk 17 version number.- See Also:
-
jdkVersion
Set the JDK version that you are using. Old JDK version numbering is supported (e.g. 1.8 for Java 8) as well as just the major JDK version alone (e.g. 8) is supported. This property only considers features from officially released Java versions as supported. Features introduced in preview releases are not considered supported until they are included in a non-preview release.
-
-
Constructor Details
-
RedundantModifierCheck
public RedundantModifierCheck()
-
-
Method Details
-
setJdkVersion
Setter to set the JDK version that you are using. Old JDK version numbering is supported (e.g. 1.8 for Java 8) as well as just the major JDK version alone (e.g. 8) is supported. This property only considers features from officially released Java versions as supported. Features introduced in preview releases are not considered supported until they are included in a non-preview release.- Parameters:
jdkVersion- the Java version- Since:
- 10.18.0
-
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:
-
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:
-
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:
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
processLambdaParameters
Process lambda parameters.- Parameters:
lambdaAst- node of typeTokenTypes.LAMBDA
-
checkUnnamedVariables
Check if the variable is unnamed and has redundant final modifier.- Parameters:
ast- node of typeTokenTypes.VARIABLE_DEForTokenTypes.PATTERN_VARIABLE_DEForTokenTypes.PARAMETER_DEF
-
isUnnamedVariable
Check if the variable is unnamed.- Parameters:
ast- node of typeTokenTypes.VARIABLE_DEForTokenTypes.PATTERN_VARIABLE_DEForTokenTypes.PARAMETER_DEF- Returns:
- true if the variable is unnamed
-
checkConstructorModifiers
Check modifiers of constructor.- Parameters:
ctorDefAst- ast node of typeTokenTypes.CTOR_DEF
-
checkInterfaceModifiers
Checks if interface has proper modifiers.- Parameters:
ast- interface to check
-
checkEnumConstructorModifiers
Check if enum constructor has proper modifiers.- Parameters:
ast- constructor of enum
-
processInterfaceOrAnnotation
Do validation of interface of annotation.- Parameters:
ast- token AST
-
processMethods
Process validation of Methods.- Parameters:
ast- method AST
-
processAbstractMethodParameters
Process validation of parameters for Methods with no definition.- Parameters:
ast- method AST
-
checkClassConstructorModifiers
Check if class constructor has proper modifiers.- Parameters:
classCtorAst- class constructor ast
-
processResources
Checks if given resource has redundant modifiers.- Parameters:
ast- ast
-
checkForRedundantModifier
Checks if given ast has a redundant modifier.- Parameters:
ast- astmodifierTypes- The modifiers to check for.
-
isClassProtected
Checks if given class ast has protected modifier.- Parameters:
classDef- class ast- Returns:
- true if class is protected, false otherwise
-
isClassPublic
Checks if given class is accessible from "public" scope.- Parameters:
ast- class def to check- Returns:
- true if class is accessible from public scope,false otherwise
-
isEnumMember
Checks if current AST node is member of Enum.- Parameters:
ast- AST node- Returns:
- true if it is an enum member
-
isInterfaceOrAnnotationMember
Checks if current AST node is member of Interface or Annotation, not of their subnodes.- Parameters:
ast- AST node- Returns:
- true or false
-
isAnnotatedWithSafeVarargs
Checks if method definition is annotated with. SafeVarargs annotation- Parameters:
methodDef- method definition node- Returns:
- true or false
-
getMethodAnnotationsList
Gets the list of annotations on method definition.- Parameters:
methodDef- method definition node- Returns:
- List of annotations
-