Class VisibilityModifierCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class VisibilityModifierCheck extends AbstractCheck
Checks visibility of class members. Only static final, immutable or annotated by specified annotation members may be public; other class members must be private unless the propertyprotectedAllowed
orpackageAllowed
is set.Public members are not flagged if the name matches the public member regular expression (contains
"^serialVersionUID$"
by default).Note that Checkstyle 2 used to include
"^f[A-Z][a-zA-Z0-9]*$"
in the default pattern to allow names used in container-managed persistence for Enterprise JavaBeans (EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to have public access for persistent fields, so the default has been changed.Rationale: Enforce encapsulation.
Check also has options making it less strict:
ignoreAnnotationCanonicalNames- the list of annotations which ignore variables in consideration. If user want to provide short annotation name that type will match to any named the same type without consideration of package.
allowPublicFinalFields- which allows public final fields.
allowPublicImmutableFields- which allows immutable fields to be declared as public if defined in final class.
Field is known to be immutable if:
- It's declared as final
- Has either a primitive type or instance of class user defined to be immutable (such as String, ImmutableCollection from Guava, etc.)
Classes known to be immutable are listed in immutableClassCanonicalNames by their canonical names.
Property Rationale: Forcing all fields of class to have private modifier by default is good in most cases, but in some cases it drawbacks in too much boilerplate get/set code. One of such cases are immutable classes.
Restriction: Check doesn't check if class is immutable, there's no checking if accessory methods are missing and all fields are immutable, we only check if current field is immutable or final. Under the flag allowPublicImmutableFields, the enclosing class must also be final, to encourage immutability. Under the flag allowPublicFinalFields, the final modifier on the enclosing class is optional.
Star imports are out of scope of this Check. So if one of type imported via star import collides with user specified one by its short name - there won't be Check's violation.
-
Property
allowPublicFinalFields
- Allow final fields to be declared as public. Type isboolean
. Default value isfalse
. -
Property
allowPublicImmutableFields
- Allow immutable fields to be declared as public if defined in final class. Type isboolean
. Default value isfalse
. -
Property
ignoreAnnotationCanonicalNames
- Specify annotations canonical names which ignore variables in consideration. Type isjava.lang.String[]
. Default value iscom.google.common.annotations.VisibleForTesting, org.junit.ClassRule, org.junit.Rule
. -
Property
immutableClassCanonicalNames
- Specify immutable classes canonical names. Type isjava.lang.String[]
. Default value isjava.io.File, java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, java.lang.StackTraceElement, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.net.Inet4Address, java.net.Inet6Address, java.net.InetSocketAddress, java.net.URI, java.net.URL, java.util.Locale, java.util.UUID
. -
Property
packageAllowed
- Control whether package visible members are allowed. Type isboolean
. Default value isfalse
. -
Property
protectedAllowed
- Control whether protected members are allowed. Type isboolean
. Default value isfalse
. -
Property
publicMemberPattern
- Specify pattern for public members that should be ignored. Type isjava.util.regex.Pattern
. Default value is"^serialVersionUID$"
.
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
variable.notPrivate
- Since:
- 3.0
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private boolean
allowPublicFinalFields
Allow final fields to be declared as public.private boolean
allowPublicImmutableFields
Allow immutable fields to be declared as public if defined in final class.private static Set<String>
DEFAULT_IGNORE_ANNOTATIONS
Default ignore annotations canonical names.private static Set<String>
DEFAULT_IMMUTABLE_TYPES
Default immutable types canonical names.private static String[]
EXPLICIT_MODS
Contains explicit access modifiers.private static String
FINAL_KEYWORD
Name for 'final' keyword.private Set<String>
ignoreAnnotationCanonicalNames
Specify annotations canonical names which ignore variables in consideration.private Set<String>
ignoreAnnotationShortNames
Set of ignore annotations short names.private Set<String>
immutableClassCanonicalNames
Specify immutable classes canonical names.private Set<String>
immutableClassShortNames
Set of immutable classes short names.static String
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.private static String
PACKAGE_ACCESS_MODIFIER
Name for implicit 'package' access modifier.private boolean
packageAllowed
Control whether package visible members are allowed.private static String
PRIVATE_ACCESS_MODIFIER
Name for 'private' access modifier.private static String
PROTECTED_ACCESS_MODIFIER
Name for 'protected' access modifier.private boolean
protectedAllowed
Control whether protected members are allowed.private static String
PUBLIC_ACCESS_MODIFIER
Name for 'public' access modifier.private Pattern
publicMemberPattern
Specify pattern for public members that should be ignored.private static String
STATIC_KEYWORD
Name for 'static' keyword.
-
Constructor Summary
Constructors Constructor Description VisibilityModifierCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private boolean
areImmutableTypeArguments(Collection<String> typeArgsClassNames)
Checks whether all generic type arguments are immutable.void
beginTree(DetailAST rootAst)
Called before the starting to process a tree.private DetailAST
findMatchingAnnotation(DetailAST variableDef)
Checks whether the AST is annotated with an annotation containing the passed in regular expression and return the AST representing that annotation.int[]
getAcceptableTokens()
The configurable token set.private static String
getCanonicalName(DetailAST type)
Gets canonical type's name from givenTYPE
node.private static String
getClassShortName(String canonicalClassName)
Gets the short class name from given canonical name.private static Set<String>
getClassShortNames(Set<String> canonicalClassNames)
Converts canonical class names to short names.int[]
getDefaultTokens()
Returns the default token a check is interested in.private static DetailAST
getGenericTypeArgs(DetailAST type, boolean isCanonicalName)
Returns generic type arguments token.private static Set<String>
getModifiers(DetailAST defAST)
Returns the set of modifier Strings for a VARIABLE_DEF or CLASS_DEF AST.private static DetailAST
getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst)
Gets the next node of a syntactical tree (child of a current node or sibling of a current node, or sibling of a parent of a current node).int[]
getRequiredTokens()
The tokens that this check must be registered for.private static List<String>
getTypeArgsClassNames(DetailAST typeArgs)
Returns a list of type parameters class names.private static String
getVisibilityScope(DetailAST variableDef)
Returns the visibility scope for the variable.private boolean
hasIgnoreAnnotation(DetailAST variableDef)
Checks if variable def has ignore annotation.private boolean
hasProperAccessModifier(DetailAST variableDef, String variableName)
Checks if current variable has proper access modifier according to Check's options.private boolean
isAllowedPublicField(DetailAST variableDef)
Checks whether the variable satisfies the public field check.private static boolean
isAnonymousClassVariable(DetailAST variableDef)
Checks if current variable definition is definition of an anonymous class.private static boolean
isCanonicalName(DetailAST type)
Checks whether type definition is in canonical form.private static boolean
isFinalField(DetailAST variableDef)
Checks whether current field is final.private boolean
isIgnoredPublicMember(String variableName, String variableScope)
Checks whether variable belongs to public members that should be ignored.private boolean
isImmutableField(DetailAST variableDef)
Checks if current field is immutable: has final modifier and either a primitive type or instance of class known to be immutable (such as String, ImmutableCollection from Guava, etc.).private boolean
isImmutableFieldDefinedInFinalClass(DetailAST variableDef)
Checks whether immutable field is defined in final class.private static boolean
isPrimitive(DetailAST type)
Checks if current type is primitive type (int, short, float, boolean, double, etc.).private static boolean
isStarImport(DetailAST importAst)
Checks if current import is star import.private static boolean
isStaticFinalVariable(DetailAST variableDef)
Checks whether variable has static final modifiers.void
setAllowPublicFinalFields(boolean allow)
Setter to allow final fields to be declared as public.void
setAllowPublicImmutableFields(boolean allow)
Setter to allow immutable fields to be declared as public if defined in final class.void
setIgnoreAnnotationCanonicalNames(String... annotationNames)
Setter to specify annotations canonical names which ignore variables in consideration.void
setImmutableClassCanonicalNames(String... classNames)
Setter to specify immutable classes canonical names.void
setPackageAllowed(boolean packageAllowed)
Setter to control whether package visible members are allowed.void
setProtectedAllowed(boolean protectedAllowed)
Setter to control whether protected members are allowed.void
setPublicMemberPattern(Pattern pattern)
Setter to specify pattern for public members that should be ignored.private void
visitImport(DetailAST importAst)
Checks imported type.void
visitToken(DetailAST ast)
Called to process a token.private void
visitVariableDef(DetailAST variableDef)
Checks access modifier of given variable.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY
public static final String MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
DEFAULT_IMMUTABLE_TYPES
private static final Set<String> DEFAULT_IMMUTABLE_TYPES
Default immutable types canonical names.
-
DEFAULT_IGNORE_ANNOTATIONS
private static final Set<String> DEFAULT_IGNORE_ANNOTATIONS
Default ignore annotations canonical names.
-
PUBLIC_ACCESS_MODIFIER
private static final String PUBLIC_ACCESS_MODIFIER
Name for 'public' access modifier.- See Also:
- Constant Field Values
-
PRIVATE_ACCESS_MODIFIER
private static final String PRIVATE_ACCESS_MODIFIER
Name for 'private' access modifier.- See Also:
- Constant Field Values
-
PROTECTED_ACCESS_MODIFIER
private static final String PROTECTED_ACCESS_MODIFIER
Name for 'protected' access modifier.- See Also:
- Constant Field Values
-
PACKAGE_ACCESS_MODIFIER
private static final String PACKAGE_ACCESS_MODIFIER
Name for implicit 'package' access modifier.- See Also:
- Constant Field Values
-
STATIC_KEYWORD
private static final String STATIC_KEYWORD
Name for 'static' keyword.- See Also:
- Constant Field Values
-
FINAL_KEYWORD
private static final String FINAL_KEYWORD
Name for 'final' keyword.- See Also:
- Constant Field Values
-
EXPLICIT_MODS
private static final String[] EXPLICIT_MODS
Contains explicit access modifiers.
-
publicMemberPattern
private Pattern publicMemberPattern
Specify pattern for public members that should be ignored.
-
ignoreAnnotationShortNames
private Set<String> ignoreAnnotationShortNames
Set of ignore annotations short names.
-
immutableClassShortNames
private Set<String> immutableClassShortNames
Set of immutable classes short names.
-
ignoreAnnotationCanonicalNames
private Set<String> ignoreAnnotationCanonicalNames
Specify annotations canonical names which ignore variables in consideration.
-
protectedAllowed
private boolean protectedAllowed
Control whether protected members are allowed.
-
packageAllowed
private boolean packageAllowed
Control whether package visible members are allowed.
-
allowPublicImmutableFields
private boolean allowPublicImmutableFields
Allow immutable fields to be declared as public if defined in final class.
-
allowPublicFinalFields
private boolean allowPublicFinalFields
Allow final fields to be declared as public.
-
immutableClassCanonicalNames
private Set<String> immutableClassCanonicalNames
Specify immutable classes canonical names.
-
-
Constructor Detail
-
VisibilityModifierCheck
public VisibilityModifierCheck()
-
-
Method Detail
-
setIgnoreAnnotationCanonicalNames
public void setIgnoreAnnotationCanonicalNames(String... annotationNames)
Setter to specify annotations canonical names which ignore variables in consideration.- Parameters:
annotationNames
- array of ignore annotations canonical names.- Since:
- 6.5
-
setProtectedAllowed
public void setProtectedAllowed(boolean protectedAllowed)
Setter to control whether protected members are allowed.- Parameters:
protectedAllowed
- whether protected members are allowed- Since:
- 3.0
-
setPackageAllowed
public void setPackageAllowed(boolean packageAllowed)
Setter to control whether package visible members are allowed.- Parameters:
packageAllowed
- whether package visible members are allowed- Since:
- 3.0
-
setPublicMemberPattern
public void setPublicMemberPattern(Pattern pattern)
Setter to specify pattern for public members that should be ignored.- Parameters:
pattern
- pattern for public members to ignore.- Since:
- 3.0
-
setAllowPublicImmutableFields
public void setAllowPublicImmutableFields(boolean allow)
Setter to allow immutable fields to be declared as public if defined in final class.- Parameters:
allow
- user's value.- Since:
- 6.4
-
setAllowPublicFinalFields
public void setAllowPublicFinalFields(boolean allow)
Setter to allow final fields to be declared as public.- Parameters:
allow
- user's value.- Since:
- 7.0
-
setImmutableClassCanonicalNames
public void setImmutableClassCanonicalNames(String... classNames)
Setter to specify immutable classes canonical names.- Parameters:
classNames
- array of immutable types canonical names.- Since:
- 6.4.1
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheck
The 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:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
beginTree
public void beginTree(DetailAST rootAst)
Description copied from class:AbstractCheck
Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTree
in classAbstractCheck
- Parameters:
rootAst
- the root of the tree
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
isAnonymousClassVariable
private static boolean isAnonymousClassVariable(DetailAST variableDef)
Checks if current variable definition is definition of an anonymous class.- Parameters:
variableDef
-VARIABLE_DEF
- Returns:
- true if current variable definition is definition of an anonymous class.
-
visitVariableDef
private void visitVariableDef(DetailAST variableDef)
Checks access modifier of given variable. If it is not proper according to Check - puts violation on it.- Parameters:
variableDef
- variable to check.
-
hasIgnoreAnnotation
private boolean hasIgnoreAnnotation(DetailAST variableDef)
Checks if variable def has ignore annotation.- Parameters:
variableDef
-VARIABLE_DEF
- Returns:
- true if variable def has ignore annotation.
-
visitImport
private void visitImport(DetailAST importAst)
Checks imported type. If type's canonical name was not specified in immutableClassCanonicalNames, but its short name collides with one from immutableClassShortNames - removes it from the last one.- Parameters:
importAst
-Import
-
isStarImport
private static boolean isStarImport(DetailAST importAst)
Checks if current import is star import. E.g.:import java.util.*;
- Parameters:
importAst
-Import
- Returns:
- true if it is star import
-
hasProperAccessModifier
private boolean hasProperAccessModifier(DetailAST variableDef, String variableName)
Checks if current variable has proper access modifier according to Check's options.- Parameters:
variableDef
- Variable definition node.variableName
- Variable's name.- Returns:
- true if variable has proper access modifier.
-
isStaticFinalVariable
private static boolean isStaticFinalVariable(DetailAST variableDef)
Checks whether variable has static final modifiers.- Parameters:
variableDef
- Variable definition node.- Returns:
- true of variable has static final modifiers.
-
isIgnoredPublicMember
private boolean isIgnoredPublicMember(String variableName, String variableScope)
Checks whether variable belongs to public members that should be ignored.- Parameters:
variableName
- Variable's name.variableScope
- Variable's scope.- Returns:
- true if variable belongs to public members that should be ignored.
-
isAllowedPublicField
private boolean isAllowedPublicField(DetailAST variableDef)
Checks whether the variable satisfies the public field check.- Parameters:
variableDef
- Variable definition node.- Returns:
- true if allowed.
-
isImmutableFieldDefinedInFinalClass
private boolean isImmutableFieldDefinedInFinalClass(DetailAST variableDef)
Checks whether immutable field is defined in final class.- Parameters:
variableDef
- Variable definition node.- Returns:
- true if immutable field is defined in final class.
-
getModifiers
private static Set<String> getModifiers(DetailAST defAST)
Returns the set of modifier Strings for a VARIABLE_DEF or CLASS_DEF AST.- Parameters:
defAST
- AST for a variable or class definition.- Returns:
- the set of modifier Strings for defAST.
-
getVisibilityScope
private static String getVisibilityScope(DetailAST variableDef)
Returns the visibility scope for the variable.- Parameters:
variableDef
- Variable definition node.- Returns:
- one of "public", "private", "protected", "package"
-
isImmutableField
private boolean isImmutableField(DetailAST variableDef)
Checks if current field is immutable: has final modifier and either a primitive type or instance of class known to be immutable (such as String, ImmutableCollection from Guava, etc.). Classes known to be immutable are listed inimmutableClassCanonicalNames
- Parameters:
variableDef
- Field in consideration.- Returns:
- true if field is immutable.
-
isCanonicalName
private static boolean isCanonicalName(DetailAST type)
Checks whether type definition is in canonical form.- Parameters:
type
- type definition token.- Returns:
- true if type definition is in canonical form.
-
getGenericTypeArgs
private static DetailAST getGenericTypeArgs(DetailAST type, boolean isCanonicalName)
Returns generic type arguments token.- Parameters:
type
- type token.isCanonicalName
- whether type name is in canonical form.- Returns:
- generic type arguments token.
-
getTypeArgsClassNames
private static List<String> getTypeArgsClassNames(DetailAST typeArgs)
Returns a list of type parameters class names.- Parameters:
typeArgs
- type arguments token.- Returns:
- a list of type parameters class names.
-
areImmutableTypeArguments
private boolean areImmutableTypeArguments(Collection<String> typeArgsClassNames)
Checks whether all generic type arguments are immutable. If at least one argument is mutable, we assume that the whole list of type arguments is mutable.- Parameters:
typeArgsClassNames
- type arguments class names.- Returns:
- true if all generic type arguments are immutable.
-
isFinalField
private static boolean isFinalField(DetailAST variableDef)
Checks whether current field is final.- Parameters:
variableDef
- field in consideration.- Returns:
- true if current field is final.
-
isPrimitive
private static boolean isPrimitive(DetailAST type)
Checks if current type is primitive type (int, short, float, boolean, double, etc.). As primitive types have special tokens for each one, such as: LITERAL_INT, LITERAL_BOOLEAN, etc. So, if type's identifier differs fromIDENT
token - it's a primitive type.- Parameters:
type
- AstTYPE
node.- Returns:
- true if current type is primitive type.
-
getCanonicalName
private static String getCanonicalName(DetailAST type)
Gets canonical type's name from givenTYPE
node.- Parameters:
type
- DetailASTTYPE
node.- Returns:
- canonical type's name
-
getNextSubTreeNode
private static DetailAST getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst)
Gets the next node of a syntactical tree (child of a current node or sibling of a current node, or sibling of a parent of a current node).- Parameters:
currentNodeAst
- Current node in consideringsubTreeRootAst
- SubTree root- Returns:
- Current node after bypassing, if current node reached the root of a subtree method returns null
-
getClassShortNames
private static Set<String> getClassShortNames(Set<String> canonicalClassNames)
Converts canonical class names to short names.- Parameters:
canonicalClassNames
- the set of canonical class names.- Returns:
- the set of short names of classes.
-
getClassShortName
private static String getClassShortName(String canonicalClassName)
Gets the short class name from given canonical name.- Parameters:
canonicalClassName
- canonical class name.- Returns:
- short name of class.
-
findMatchingAnnotation
private DetailAST findMatchingAnnotation(DetailAST variableDef)
Checks whether the AST is annotated with an annotation containing the passed in regular expression and return the AST representing that annotation.This method will not look for imports or package statements to detect the passed in annotation.
To check if an AST contains a passed in annotation taking into account fully-qualified names (ex: java.lang.Override, Override) this method will need to be called twice. Once for each name given.
- Parameters:
variableDef
-variable def node
.- Returns:
- the AST representing the first such annotation or null if no such annotation was found
-
-