Class AnnotationLocationCheck
- 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.annotation.AnnotationLocationCheck
-
- All Implemented Interfaces:
Configurable,Contextualizable
public class AnnotationLocationCheck extends AbstractCheck
Check location of annotation on language elements. By default, Check enforce to locate annotations immediately after documentation block and before target element, annotation should be located on separate line from target element.Attention: Annotations among modifiers are ignored (looks like false-negative) as there might be a problem with annotations for return types.
public @Nullable Long getStartTimeOrNull() { ... }.Such annotations are better to keep close to type. Due to limitations, Checkstyle can not examine the target of an annotation.
Example:
@Override @Nullable public String getNameIfPresent() { ... }The check has the following options:
- allowSamelineMultipleAnnotations - to allow annotation to be located on the same line as the target element. Default value is false.
- allowSamelineSingleParameterlessAnnotation - to allow single parameterless annotation to be located on the same line as the target element. Default value is false.
- allowSamelineParameterizedAnnotation - to allow parameterized annotation to be located on the same line as the target element. Default value is false.
Example to allow single parameterless annotation on the same line:
@Override public int hashCode() { ... }Use the following configuration:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="false"/> <property name="allowSamelineSingleParameterlessAnnotation" value="true"/> <property name="allowSamelineParameterizedAnnotation" value="false" /> </module>
Example to allow multiple parameterized annotations on the same line:
@SuppressWarnings("deprecation") @Mock DataLoader loader;Use the following configuration:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="true"/> <property name="allowSamelineSingleParameterlessAnnotation" value="true"/> <property name="allowSamelineParameterizedAnnotation" value="true" /> </module>
Example to allow multiple parameterless annotations on the same line:
@Partial @Mock DataLoader loader;
Use the following configuration:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="true"/> <property name="allowSamelineSingleParameterlessAnnotation" value="true"/> <property name="allowSamelineParameterizedAnnotation" value="false" /> </module>
The following example demonstrates how the check validates annotation of method parameters, catch parameters, foreach, for-loop variable definitions.
Configuration:
<module name="AnnotationLocation"> <property name="allowSamelineMultipleAnnotations" value="false"/> <property name="allowSamelineSingleParameterlessAnnotation" value="false"/> <property name="allowSamelineParameterizedAnnotation" value="false" /> <property name="tokens" value="VARIABLE_DEF, PARAMETER_DEF"/> </module>Code example
... public void test(@MyAnnotation String s) { // OK ... for (@MyAnnotation char c : s.toCharArray()) { ... } // OK ... try { ... } catch (@MyAnnotation Exception ex) { ... } // OK ... for (@MyAnnotation int i = 0; i < 10; i++) { ... } // OK ... MathOperation c = (@MyAnnotation int a, @MyAnnotation int b) -> a + b; // OK ... }
-
-
Field Summary
Fields Modifier and Type Field Description private booleanallowSamelineMultipleAnnotationsIf true, it allows annotation to be located on the same line as target element.private booleanallowSamelineParameterizedAnnotationIf true, it allows parameterized annotation to be located on the same line as target element.private booleanallowSamelineSingleParameterlessAnnotationIf true, it allows single prameterless annotation to be located on the same line as target element.static java.lang.StringMSG_KEY_ANNOTATION_LOCATIONA key is pointing to the warning message text in "messages.properties" file.static java.lang.StringMSG_KEY_ANNOTATION_LOCATION_ALONEA key is pointing to the warning message text in "messages.properties" file.private static int[]SINGLELINE_ANNOTATION_PARENTSArray of single line annotation parents.
-
Constructor Summary
Constructors Constructor Description AnnotationLocationCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private voidcheckAnnotations(DetailAST modifierNode, int correctIndentation)Checks annotations positions in code: 1) Checks whether the annotations locations are correct.int[]getAcceptableTokens()The configurable token set.private static java.lang.StringgetAnnotationName(DetailAST annotation)Returns the name of the given annotation.int[]getDefaultTokens()Returns the default token a check is interested in.private static intgetExpectedAnnotationIndentation(DetailAST modifierNode)Returns an expected annotation indentation.int[]getRequiredTokens()The tokens that this check must be registered for.private static booleanhasAnnotations(DetailAST modifierNode)Checks whether a given modifier node has an annotation.private static booleanhasNodeAfter(DetailAST annotation)Checks whether an annotation node has any node after on the same line.private static booleanhasNodeBefore(DetailAST annotation)Checks whether an annotation node has any node before on the same line.private static booleanhasNodeBeside(DetailAST annotation)Checks whether an annotation node has any node before or after on the same line.static booleanisAllowedPosition(DetailAST annotation, int... allowedPositions)Checks whether position of annotation is allowed.private booleanisCorrectLocation(DetailAST annotation, boolean hasParams)Checks whether an annotation has a correct location.private static booleanisInSpecificCodeBlock(DetailAST node, int blockType)Checks whether the scope of a node is restricted to a specific code block.private static booleanisParameterized(DetailAST annotation)Checks whether an annotation has parameters.voidsetAllowSamelineMultipleAnnotations(boolean allow)Sets if allow annotation to be located on the same line as target element.voidsetAllowSamelineParameterizedAnnotation(boolean allow)Sets if allow parameterized annotation to be located on the same line as target element.voidsetAllowSamelineSingleParameterlessAnnotation(boolean allow)Sets if allow same line single parameterless annotation.voidvisitToken(DetailAST ast)Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, 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_ANNOTATION_LOCATION_ALONE
public static final java.lang.String MSG_KEY_ANNOTATION_LOCATION_ALONE
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_KEY_ANNOTATION_LOCATION
public static final java.lang.String MSG_KEY_ANNOTATION_LOCATION
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
SINGLELINE_ANNOTATION_PARENTS
private static final int[] SINGLELINE_ANNOTATION_PARENTS
Array of single line annotation parents.
-
allowSamelineSingleParameterlessAnnotation
private boolean allowSamelineSingleParameterlessAnnotation
If true, it allows single prameterless annotation to be located on the same line as target element.
-
allowSamelineParameterizedAnnotation
private boolean allowSamelineParameterizedAnnotation
If true, it allows parameterized annotation to be located on the same line as target element.
-
allowSamelineMultipleAnnotations
private boolean allowSamelineMultipleAnnotations
If true, it allows annotation to be located on the same line as target element.
-
-
Method Detail
-
setAllowSamelineSingleParameterlessAnnotation
public final void setAllowSamelineSingleParameterlessAnnotation(boolean allow)
Sets if allow same line single parameterless annotation.- Parameters:
allow- User's value of allowSamelineSingleParameterlessAnnotation.
-
setAllowSamelineParameterizedAnnotation
public final void setAllowSamelineParameterizedAnnotation(boolean allow)
Sets if allow parameterized annotation to be located on the same line as target element.- Parameters:
allow- User's value of allowSamelineParameterizedAnnotation.
-
setAllowSamelineMultipleAnnotations
public final void setAllowSamelineMultipleAnnotations(boolean allow)
Sets if allow annotation to be located on the same line as target element.- Parameters:
allow- User's value of allowSamelineMultipleAnnotations.
-
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:
TokenTypes
-
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:
TokenTypes
-
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:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
hasAnnotations
private static boolean hasAnnotations(DetailAST modifierNode)
Checks whether a given modifier node has an annotation.- Parameters:
modifierNode- modifier node.- Returns:
- true if the given modifier node has the annotation.
-
getExpectedAnnotationIndentation
private static int getExpectedAnnotationIndentation(DetailAST modifierNode)
Returns an expected annotation indentation. The expected indentation should be the same as the indentation of the node which is the parent of the target modifier node.- Parameters:
modifierNode- modifier node.- Returns:
- the annotation indentation.
-
checkAnnotations
private void checkAnnotations(DetailAST modifierNode, int correctIndentation)
Checks annotations positions in code: 1) Checks whether the annotations locations are correct. 2) Checks whether the annotations have the valid indentation level.- Parameters:
modifierNode- modifiers node.correctIndentation- correct indentation of the annotation.
-
isParameterized
private static boolean isParameterized(DetailAST annotation)
Checks whether an annotation has parameters.- Parameters:
annotation- annotation node.- Returns:
- true if the annotation has parameters.
-
getAnnotationName
private static java.lang.String getAnnotationName(DetailAST annotation)
Returns the name of the given annotation.- Parameters:
annotation- annotation node.- Returns:
- annotation name.
-
isCorrectLocation
private boolean isCorrectLocation(DetailAST annotation, boolean hasParams)
Checks whether an annotation has a correct location. Annotation location is considered correct ifallowSamelineMultipleAnnotationsis set to true. The method also: 1) checks parameterized annotation location considering the value ofallowSamelineParameterizedAnnotation; 2) checks parameterless annotation location considering the value ofallowSamelineSingleParameterlessAnnotation; 3) checks annotation location considering the elements ofSINGLELINE_ANNOTATION_PARENTS;- Parameters:
annotation- annotation node.hasParams- whether an annotation has parameters.- Returns:
- true if the annotation has a correct location.
-
hasNodeBefore
private static boolean hasNodeBefore(DetailAST annotation)
Checks whether an annotation node has any node before on the same line.- Parameters:
annotation- annotation node.- Returns:
- true if an annotation node has any node before on the same line.
-
hasNodeBeside
private static boolean hasNodeBeside(DetailAST annotation)
Checks whether an annotation node has any node before or after on the same line.- Parameters:
annotation- annotation node.- Returns:
- true if an annotation node has any node before or after on the same line.
-
hasNodeAfter
private static boolean hasNodeAfter(DetailAST annotation)
Checks whether an annotation node has any node after on the same line.- Parameters:
annotation- annotation node.- Returns:
- true if an annotation node has any node after on the same line.
-
isAllowedPosition
public static boolean isAllowedPosition(DetailAST annotation, int... allowedPositions)
Checks whether position of annotation is allowed.- Parameters:
annotation- annotation token.allowedPositions- an array of allowed annotation positions.- Returns:
- true if position of annotation is allowed.
-
isInSpecificCodeBlock
private static boolean isInSpecificCodeBlock(DetailAST node, int blockType)
Checks whether the scope of a node is restricted to a specific code block.- Parameters:
node- node.blockType- block type.- Returns:
- true if the scope of a node is restricted to a specific code block.
-
-