Class VisibilityModifierCheck
- All Implemented Interfaces:
Configurable,Contextualizable
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 property protectedAllowed
or packageAllowed 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 will 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 and 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
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$". -
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
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
ignoreAnnotationCanonicalNames- Specify the list of 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.
To configure the check:
<module name="VisibilityModifier"/>
To configure the check so that it allows package visible members:
<module name="VisibilityModifier"> <property name="packageAllowed" value="true"/> </module>
To configure the check so that it allows no public members:
<module name="VisibilityModifier"> <property name="publicMemberPattern" value="^$"/> </module>
To configure the Check so that it allows public immutable fields (mostly for immutable classes):
<module name="VisibilityModifier"> <property name="allowPublicImmutableFields" value="true"/> </module>
Example of allowed public immutable fields:
public class ImmutableClass
{
public final ImmutableSet<String> includes; // No warning
public final ImmutableSet<String> excludes; // No warning
public final java.lang.String notes; // No warning
public final BigDecimal value; // No warning
public ImmutableClass(Collection<String> includes, Collection<String> excludes,
BigDecimal value, String notes)
{
this.includes = ImmutableSet.copyOf(includes);
this.excludes = ImmutableSet.copyOf(excludes);
this.value = value;
this.notes = notes;
}
}
To configure the Check in order to allow user specified immutable class names:
<module name="VisibilityModifier"> <property name="allowPublicImmutableFields" value="true"/> <property name="immutableClassCanonicalNames" value=" com.google.common.collect.ImmutableSet"/> </module>
Example of allowed public immutable fields:
public class ImmutableClass
{
public final ImmutableSet<String> includes; // No warning
public final ImmutableSet<String> excludes; // No warning
public final java.lang.String notes; // Warning here because
//'java.lang.String' wasn't specified as allowed class
public final int someValue; // No warning
public ImmutableClass(Collection<String> includes, Collection<String> excludes,
String notes, int someValue)
{
this.includes = ImmutableSet.copyOf(includes);
this.excludes = ImmutableSet.copyOf(excludes);
this.value = value;
this.notes = notes;
this.someValue = someValue;
}
}
Note, if allowPublicImmutableFields is set to true, the check will also check whether generic type parameters are immutable. If at least one generic type parameter is mutable, there will be a violation.
<module name="VisibilityModifier">
<property name="allowPublicImmutableFields" value="true"/>
<property name="immutableClassCanonicalNames"
value="com.google.common.collect.ImmutableSet, com.google.common.collect.ImmutableMap,
java.lang.String"/>
</module>
Example of how the check works:
public final class Test {
public final String s;
public final ImmutableSet<String> names;
public final ImmutableSet<Object> objects; // violation (Object class is mutable)
public final ImmutableMap<String, Object> links; // violation (Object class is mutable)
public Test() {
s = "Hello!";
names = ImmutableSet.of();
objects = ImmutableSet.of();
links = ImmutableMap.of();
}
}
To configure the Check passing fields annotated with @com.annotation.CustomAnnotation:
<module name="VisibilityModifier"> <property name="ignoreAnnotationCanonicalNames" value= "com.annotation.CustomAnnotation"/> </module>
Example of allowed field:
class SomeClass
{
@com.annotation.CustomAnnotation
String annotatedString; // no warning
@CustomAnnotation
String shortCustomAnnotated; // no warning
}
To configure the Check passing fields annotated with @org.junit.Rule, @org.junit.ClassRule and @com.google.common.annotations.VisibleForTesting annotations:
<module name="VisibilityModifier"/>
Example of allowed fields:
class SomeClass
{
@org.junit.Rule
public TemporaryFolder publicJUnitRule = new TemporaryFolder(); // no warning
@org.junit.ClassRule
public static TemporaryFolder publicJUnitClassRule = new TemporaryFolder(); // no warning
@com.google.common.annotations.VisibleForTesting
public String testString = ""; // no warning
}
To configure the Check passing fields annotated with short annotation name:
<module name="VisibilityModifier"> <property name="ignoreAnnotationCanonicalNames" value="CustomAnnotation"/> </module>
Example of allowed fields:
class SomeClass
{
@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
}
To understand the difference between allowPublicImmutableFields and allowPublicFinalFields options, please, study the following examples.
1) To configure the check to use only 'allowPublicImmutableFields' option:
<module name="VisibilityModifier"> <property name="allowPublicImmutableFields" value="true"/> </module>
Code example:
public class InputPublicImmutable {
public final int someIntValue; // violation
public final ImmutableSet<String> includes; // violation
public final java.lang.String notes; // violation
public final BigDecimal value; // violation
public final List list; // violation
public InputPublicImmutable(Collection<String> includes,
BigDecimal value, String notes, int someValue, List l) {
this.includes = ImmutableSet.copyOf(includes);
this.value = value;
this.notes = notes;
this.someIntValue = someValue;
this.list = l;
}
}
2) To configure the check to use only 'allowPublicFinalFields' option:
<module name="VisibilityModifier"> <property name="allowPublicFinalFields" value="true"/> </module>
Code example:
public class InputPublicImmutable {
public final int someIntValue;
public final ImmutableSet<String> includes;
public final java.lang.String notes;
public final BigDecimal value;
public final List list;
public InputPublicImmutable(Collection<String> includes,
BigDecimal value, String notes, int someValue, List l) {
this.includes = ImmutableSet.copyOf(includes);
this.value = value;
this.notes = notes;
this.someIntValue = someValue;
this.list = l;
}
}
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.api.AutomaticBean
AutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate booleanAllow final fields to be declared as public.private booleanAllow immutable fields to be declared as public if defined in final class.Default ignore annotations canonical names.Default immutable types canonical names.private static final String[]Contains explicit access modifiers.private static final StringName for 'final' keyword.Specify the list of annotations canonical names which ignore variables in consideration.List of ignore annotations short names.Specify immutable classes canonical names.List of immutable classes short names.static final StringA key is pointing to the warning message text in "messages.properties" file.private static final StringName for implicit 'package' access modifier.private booleanControl whether package visible members are allowed.private static final StringName for 'private' access modifier.private static final StringName for 'protected' access modifier.private booleanControl whether protected members are allowed.private static final StringName for 'public' access modifier.private PatternSpecify pattern for public members that should be ignored.private static final StringName for 'static' keyword. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate booleanareImmutableTypeArguments(List<String> typeArgsClassNames) Checks whether all of generic type arguments are immutable.voidCalled before the starting to process a tree.private DetailASTfindMatchingAnnotation(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[]The configurable token set.private static StringgetCanonicalName(DetailAST type) Gets canonical type's name from givenTYPEnode.private static StringgetClassShortName(String canonicalClassName) Gets the short class name from given canonical name.getClassShortNames(List<String> canonicalClassNames) Gets the list with short names classes.int[]Returns the default token a check is interested in.private static DetailASTgetGenericTypeArgs(DetailAST type, boolean isCanonicalName) Returns generic type arguments token.getModifiers(DetailAST defAST) Returns the set of modifier Strings for a VARIABLE_DEF or CLASS_DEF AST.private static DetailASTgetNextSubTreeNode(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[]The tokens that this check must be registered for.getTypeArgsClassNames(DetailAST typeArgs) Returns a list of type parameters class names.private static StringgetTypeName(DetailAST type, boolean isCanonicalName) Gets the name of type from given astTYPEnode.private static StringgetVisibilityScope(DetailAST variableDef) Returns the visibility scope for the variable.private booleanhasIgnoreAnnotation(DetailAST variableDef) Checks if variable def has ignore annotation.private booleanhasProperAccessModifier(DetailAST variableDef, String variableName) Checks if current variable has proper access modifier according to Check's options.private booleanisAllowedPublicField(DetailAST variableDef) Checks whether the variable satisfies the public field check.private static booleanisAnonymousClassVariable(DetailAST variableDef) Checks if current variable definition is definition of an anonymous class.private static booleanisCanonicalName(DetailAST type) Checks whether type definition is in canonical form.private static booleanisFinalField(DetailAST variableDef) Checks whether current field is final.private booleanisIgnoredPublicMember(String variableName, String variableScope) Checks whether variable belongs to public members that should be ignored.private booleanisImmutableField(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 and etc).private booleanisImmutableFieldDefinedInFinalClass(DetailAST variableDef) Checks whether immutable field is defined in final class.private static booleanisPrimitive(DetailAST type) Checks if current type is primitive type (int, short, float, boolean, double, etc.).private static booleanisStarImport(DetailAST importAst) Checks if current import is star import.private static booleanisStaticFinalVariable(DetailAST variableDef) Checks whether variable has static final modifiers.voidsetAllowPublicFinalFields(boolean allow) Setter to allow final fields to be declared as public.voidsetAllowPublicImmutableFields(boolean allow) Setter to allow immutable fields to be declared as public if defined in final class.voidsetIgnoreAnnotationCanonicalNames(String... annotationNames) Setter to specify the list of annotations canonical names which ignore variables in consideration.voidsetImmutableClassCanonicalNames(String... classNames) Setter to specify immutable classes canonical names.voidsetPackageAllowed(boolean packageAllowed) Setter to control whether package visible members are allowed.voidsetProtectedAllowed(boolean protectedAllowed) Setter to control whether protected members are allowed.voidsetPublicMemberPattern(Pattern pattern) Setter to specify pattern for public members that should be ignored.private voidvisitImport(DetailAST importAst) Checks imported type.voidvisitToken(DetailAST ast) Called to process a token.private voidvisitVariableDef(DetailAST variableDef) Checks access modifier of given variable.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, 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.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
DEFAULT_IMMUTABLE_TYPES
Default immutable types canonical names. -
DEFAULT_IGNORE_ANNOTATIONS
Default ignore annotations canonical names. -
PUBLIC_ACCESS_MODIFIER
Name for 'public' access modifier.- See Also:
-
PRIVATE_ACCESS_MODIFIER
Name for 'private' access modifier.- See Also:
-
PROTECTED_ACCESS_MODIFIER
Name for 'protected' access modifier.- See Also:
-
PACKAGE_ACCESS_MODIFIER
Name for implicit 'package' access modifier.- See Also:
-
STATIC_KEYWORD
Name for 'static' keyword.- See Also:
-
FINAL_KEYWORD
Name for 'final' keyword.- See Also:
-
EXPLICIT_MODS
Contains explicit access modifiers. -
publicMemberPattern
Specify pattern for public members that should be ignored. -
ignoreAnnotationShortNames
List of ignore annotations short names. -
immutableClassShortNames
List of immutable classes short names. -
ignoreAnnotationCanonicalNames
Specify the list of annotations canonical names which ignore variables in consideration. -
protectedAllowed
private boolean protectedAllowedControl whether protected members are allowed. -
packageAllowed
private boolean packageAllowedControl whether package visible members are allowed. -
allowPublicImmutableFields
private boolean allowPublicImmutableFieldsAllow immutable fields to be declared as public if defined in final class. -
allowPublicFinalFields
private boolean allowPublicFinalFieldsAllow final fields to be declared as public. -
immutableClassCanonicalNames
Specify immutable classes canonical names.
-
-
Constructor Details
-
VisibilityModifierCheck
public VisibilityModifierCheck()
-
-
Method Details
-
setIgnoreAnnotationCanonicalNames
Setter to specify the list of annotations canonical names which ignore variables in consideration.- Parameters:
annotationNames- array of ignore annotations canonical names.
-
setProtectedAllowed
public void setProtectedAllowed(boolean protectedAllowed) Setter to control whether protected members are allowed.- Parameters:
protectedAllowed- whether protected members are allowed
-
setPackageAllowed
public void setPackageAllowed(boolean packageAllowed) Setter to control whether package visible members are allowed.- Parameters:
packageAllowed- whether package visible members are allowed
-
setPublicMemberPattern
Setter to specify pattern for public members that should be ignored.- Parameters:
pattern- pattern for public members to ignore.
-
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.
-
setAllowPublicFinalFields
public void setAllowPublicFinalFields(boolean allow) Setter to allow final fields to be declared as public.- Parameters:
allow- user's value.
-
setImmutableClassCanonicalNames
Setter to specify immutable classes canonical names.- Parameters:
classNames- array of immutable types canonical names.
-
getDefaultTokens
public int[] 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:
-
getAcceptableTokens
public int[] 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:
-
getRequiredTokens
public int[] 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:
-
beginTree
Description copied from class:AbstractCheckCalled before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTreein classAbstractCheck- Parameters:
rootAst- the root of the tree
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
isAnonymousClassVariable
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
Checks access modifier of given variable. If it is not proper according to Check - puts violation on it.- Parameters:
variableDef- variable to check.
-
hasIgnoreAnnotation
Checks if variable def has ignore annotation.- Parameters:
variableDef-VARIABLE_DEF- Returns:
- true if variable def has ignore annotation.
-
visitImport
Checks imported type. If type's canonical name was not specified in immutableClassCanonicalNames, but it's short name collides with one from immutableClassShortNames - removes it from the last one.- Parameters:
importAst-Import
-
isStarImport
Checks if current import is star import. E.g.:import java.util.*;- Parameters:
importAst-Import- Returns:
- true if it is star import
-
hasProperAccessModifier
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
Checks whether variable has static final modifiers.- Parameters:
variableDef- Variable definition node.- Returns:
- true of variable has static final modifiers.
-
isIgnoredPublicMember
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
Checks whether the variable satisfies the public field check.- Parameters:
variableDef- Variable definition node.- Returns:
- true if allowed.
-
isImmutableFieldDefinedInFinalClass
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
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
Returns the visibility scope for the variable.- Parameters:
variableDef- Variable definition node.- Returns:
- one of "public", "private", "protected", "package"
-
isImmutableField
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 and etc). Classes known to be immutable are listed inimmutableClassCanonicalNames- Parameters:
variableDef- Field in consideration.- Returns:
- true if field is immutable.
-
isCanonicalName
Checks whether type definition is in canonical form.- Parameters:
type- type definition token.- Returns:
- true if type definition is in canonical form.
-
getGenericTypeArgs
Returns generic type arguments token.- Parameters:
type- type token.isCanonicalName- whether type name is in canonical form.- Returns:
- generic type arguments token.
-
getTypeArgsClassNames
Returns a list of type parameters class names.- Parameters:
typeArgs- type arguments token.- Returns:
- a list of type parameters class names.
-
areImmutableTypeArguments
Checks whether all of 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 of generic type arguments are immutable.
-
isFinalField
Checks whether current field is final.- Parameters:
variableDef- field in consideration.- Returns:
- true if current field is final.
-
getTypeName
Gets the name of type from given astTYPEnode. If type is specified via its canonical name - canonical name will be returned, else - short type's name.- Parameters:
type-TYPEnode.isCanonicalName- is given name canonical.- Returns:
- String representation of given type's name.
-
isPrimitive
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 fromIDENTtoken - it's a primitive type.- Parameters:
type- AstTYPEnode.- Returns:
- true if current type is primitive type.
-
getCanonicalName
Gets canonical type's name from givenTYPEnode.- Parameters:
type- DetailASTTYPEnode.- Returns:
- canonical type's name
-
getNextSubTreeNode
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
Gets the list with short names classes. These names are taken from array of classes canonical names.- Parameters:
canonicalClassNames- canonical class names.- Returns:
- the list of short names of classes.
-
getClassShortName
Gets the short class name from given canonical name.- Parameters:
canonicalClassName- canonical class name.- Returns:
- short name of class.
-
findMatchingAnnotation
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
-