Class VisibilityModifierCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- 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 allowProtected/Package is set.Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default).
Rationale: Enforce encapsulation.Check also has options making it less strict:
ignoreAnnotationCanonicalNames - the list of annotations canonical names which ignore variables in consideration, if user will provide short annotation name that type will match to any named the same type without consideration of package, list by default:
- org.junit.Rule
- org.junit.ClassRule
- com.google.common.annotations.VisibleForTesting
For example such public field will be skipped by default value of list above:
@org.junit.Rule public TemporaryFolder publicJUnitRule = new TemporaryFolder();
allowPublicFinalFields - which allows public final fields. Default value is false.
allowPublicImmutableFields - which allows immutable fields to be declared as public if defined in final class. Default value is false
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 and etc)
Classes known to be immutable are listed in immutableClassCanonicalNames by their canonical names. List by default:
- java.lang.String
- java.lang.Integer
- java.lang.Byte
- java.lang.Character
- java.lang.Short
- java.lang.Boolean
- java.lang.Long
- java.lang.Double
- java.lang.Float
- java.lang.StackTraceElement
- java.lang.BigInteger
- java.lang.BigDecimal
- java.io.File
- java.util.Locale
- java.util.UUID
- java.net.URL
- java.net.URI
- java.net.Inet4Address
- java.net.Inet6Address
- java.net.InetSocketAddress
User can override this list via adding canonical class names to immutableClassCanonicalNames, if user will provide short class name all that type will match to any named the same type without consideration of package.
Rationale: Forcing all fields of class to have private modified 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 by matching a name to user defined list of immutable classes and defined in final class
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.
Examples:The check will rise 3 violations if it is run with default configuration against the following code example:
public class ImmutableClass { public int intValue; // violation public java.lang.String notes; // violation public BigDecimal value; // violation public ImmutableClass(int intValue, BigDecimal value, String notes) { this.intValue = intValue; this.value = value; this.notes = notes; } }
To configure the Check passing fields of type com.google.common.collect.ImmutableSet and java.util.List:
<module name="VisibilityModifier"> <property name="allowPublicImmutableFields" value="true"/> <property name="immutableClassCanonicalNames" value="java.util.List, com.google.common.collect.ImmutableSet"/> </module>
public final class ImmutableClass { public final ImmutableSet<String> includes; // No warning public final ImmutableSet<String> excludes; // No warning public final BigDecimal value; // Warning here, type BigDecimal isn't specified as immutable public ImmutableClass(Collection<String> includes, Collection<String> excludes, BigDecimal value) { this.includes = ImmutableSet.copyOf(includes); this.excludes = ImmutableSet.copyOf(excludes); this.value = value; this.notes = notes; } }
To configure the Check passing fields annotated with
@com.annotation.CustomAnnotation
:<module name="VisibilityModifier"> <property name="ignoreAnnotationCanonicalNames" value=" com.annotation.CustomAnnotation"/> </module>
@com.annotation.CustomAnnotation String customAnnotated; // No warning
@CustomAnnotation String shortCustomAnnotated; // No warning
To configure the Check passing fields annotated with short annotation name
@CustomAnnotation
:<module name="VisibilityModifier"> <property name="ignoreAnnotationCanonicalNames" value="CustomAnnotation"/> </module>
@CustomAnnotation String customAnnotated; // No warning
@com.annotation.CustomAnnotation String customAnnotated1; // No warning
@mypackage.annotation.CustomAnnotation String customAnnotatedAnotherPackage; // another package but short name matches // so no violation
- Author:
- Aleksey Nesterenko
-
-
Constructor Summary
Constructors Constructor Description VisibilityModifierCheck()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
beginTree(DetailAST rootAst)
Called before the starting to process a tree.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
setAllowPublicFinalFields(boolean allow)
Sets whether public final fields are allowed.void
setAllowPublicImmutableFields(boolean allow)
Sets whether public immutable fields are allowed.void
setIgnoreAnnotationCanonicalNames(String... annotationNames)
Set the list of ignore annotations.void
setImmutableClassCanonicalNames(String... classNames)
Set the list of immutable classes types names.void
setPackageAllowed(boolean packageAllowed)
Set whether package visible members are allowed.void
setProtectedAllowed(boolean protectedAllowed)
Set whether protected members are allowed.void
setPublicMemberPattern(Pattern pattern)
Set the pattern for public members to ignore.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
destroy, finishTree, getClassLoader, getFileContents, getLine, getLines, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, setClassLoader, setFileContents, setMessages, setTabWidth, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, log, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, finishLocalSetup, 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
-
-
Constructor Detail
-
VisibilityModifierCheck
public VisibilityModifierCheck()
-
-
Method Detail
-
setIgnoreAnnotationCanonicalNames
public void setIgnoreAnnotationCanonicalNames(String... annotationNames)
Set the list of ignore annotations.- Parameters:
annotationNames
- array of ignore annotations canonical names.
-
setProtectedAllowed
public void setProtectedAllowed(boolean protectedAllowed)
Set whether protected members are allowed.- Parameters:
protectedAllowed
- whether protected members are allowed
-
setPackageAllowed
public void setPackageAllowed(boolean packageAllowed)
Set whether package visible members are allowed.- Parameters:
packageAllowed
- whether package visible members are allowed
-
setPublicMemberPattern
public void setPublicMemberPattern(Pattern pattern)
Set the pattern for public members to ignore.- Parameters:
pattern
- pattern for public members to ignore.
-
setAllowPublicImmutableFields
public void setAllowPublicImmutableFields(boolean allow)
Sets whether public immutable fields are allowed.- Parameters:
allow
- user's value.
-
setAllowPublicFinalFields
public void setAllowPublicFinalFields(boolean allow)
Sets whether public final fields are allowed.- Parameters:
allow
- user's value.
-
setImmutableClassCanonicalNames
public void setImmutableClassCanonicalNames(String... classNames)
Set the list of immutable classes types names.- Parameters:
classNames
- array of immutable types canonical names.
-
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
-
-