Class JavadocMethodCheck
- 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.javadoc.JavadocMethodCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class JavadocMethodCheck extends AbstractCheck
Checks the Javadoc of a method or constructor.Violates parameters and type parameters for which no param tags are present can be suppressed by defining property
allowMissingParamTags
.Violates methods which return non-void but for which no return tag is present can be suppressed by defining property
allowMissingReturnTag
.Violates exceptions which are declared to be thrown (by
throws
in the method signature or bythrow new
in the method body), but for which no throws tag is present by activation of propertyvalidateThrows
. Note thatthrow new
is not checked in the following places:- Inside a try block (with catch). It is not possible to determine if the thrown exception can be caught by the catch block as there is no knowledge of the inheritance hierarchy, so the try block is ignored entirely. However, catch and finally blocks, as well as try blocks without catch, are still checked.
- Local classes, anonymous classes and lambda expressions. It is not known when the throw statements inside such classes are going to be evaluated, so they are ignored.
ATTENTION: Checkstyle does not have information about hierarchy of exception types so usage of base class is considered as separate exception type. As workaround, you need to specify both types in javadoc (parent and exact type).
Javadoc is not required on a method that is tagged with the
@Override
annotation. However, under Java 5 it is not possible to mark a method required for an interface (this was corrected under Java 6). Hence, Checkstyle supports using the convention of using a single{@inheritDoc}
tag instead of all the other tags.Note that only inheritable items will allow the
{@inheritDoc}
tag to be used in place of comments. Static methods at all visibilities, private non-static methods and constructors are not inheritable.For example, if the following method is implementing a method required by an interface, then the Javadoc could be done as:
/** {@inheritDoc} */ public int checkReturnTag(final int aTagIndex, JavadocTag[] aTags, int aLineNo)
-
Property
accessModifiers
- Specify the access modifiers where Javadoc comments are checked. Type iscom.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption[]
. Default value ispublic, protected, package, private
. -
Property
allowMissingParamTags
- Control whether to ignore violations when a method has parameters but does not have matchingparam
tags in the javadoc. Type isboolean
. Default value isfalse
. -
Property
allowMissingReturnTag
- Control whether to ignore violations when a method returns non-void type and does not have areturn
tag in the javadoc. Type isboolean
. Default value isfalse
. -
Property
allowedAnnotations
- Specify annotations that allow missed documentation. Type isjava.lang.String[]
. Default value isOverride
. -
Property
validateThrows
- Control whether to validatethrows
tags. Type isboolean
. Default value isfalse
. -
Property
tokens
- tokens to check Type isjava.lang.String[]
. Validation type istokenSet
. Default value is: METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, COMPACT_CTOR_DEF.
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
javadoc.classInfo
-
javadoc.duplicateTag
-
javadoc.expectedTag
-
javadoc.invalidInheritDoc
-
javadoc.return.expected
-
javadoc.unusedTag
-
javadoc.unusedTagGeneral
- Since:
- 3.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static class
JavadocMethodCheck.ClassInfo
Contains class'sToken
.private static class
JavadocMethodCheck.ExceptionInfo
Stores useful information about declared exception.private static class
JavadocMethodCheck.Token
Represents text element with location in the text.-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private AccessModifierOption[]
accessModifiers
Specify the access modifiers where Javadoc comments are checked.private Set<String>
allowedAnnotations
Specify annotations that allow missed documentation.private boolean
allowMissingParamTags
Control whether to ignore violations when a method has parameters but does not have matchingparam
tags in the javadoc.private boolean
allowMissingReturnTag
Control whether to ignore violations when a method returns non-void type and does not have areturn
tag in the javadoc.private static String
ELEMENT_END
Html element end symbol.private static String
ELEMENT_START
Html element start symbol.private static String
END_JAVADOC
Multiline finished at end of comment.private static Pattern
MATCH_JAVADOC_ARG
Compiled regexp to match Javadoc tags that take an argument.private static Pattern
MATCH_JAVADOC_ARG_MISSING_DESCRIPTION
Compiled regexp to match Javadoc tags with argument but with missing description.private static Pattern
MATCH_JAVADOC_MULTILINE_CONT
Compiled regexp to look for a continuation of the comment.private static Pattern
MATCH_JAVADOC_NOARG
Compiled regexp to match Javadoc tags with no argument.private static Pattern
MATCH_JAVADOC_NOARG_CURLY
Compiled regexp to match Javadoc tags with no argument and {}.private static Pattern
MATCH_JAVADOC_NOARG_MULTILINE_START
Compiled regexp to match first part of multilineJavadoc tags.static String
MSG_CLASS_INFO
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_DUPLICATE_TAG
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_EXPECTED_TAG
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_INVALID_INHERIT_DOC
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_RETURN_EXPECTED
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_UNUSED_TAG
A key is pointing to the warning message text in "messages.properties" file.static String
MSG_UNUSED_TAG_GENERAL
A key is pointing to the warning message text in "messages.properties" file.private static String
NEXT_TAG
Multiline finished at next Javadoc.private boolean
validateThrows
Control whether to validatethrows
tags.
-
Constructor Summary
Constructors Constructor Description JavadocMethodCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private static int
calculateTagColumn(MatchResult javadocTagMatchResult, int lineNumber, int startColumnNumber)
Calculates column number using Javadoc tag matcher.private void
checkComment(DetailAST ast, TextBlock comment)
Checks the Javadoc for a method.private void
checkParamTags(List<JavadocTag> tags, DetailAST parent, boolean reportExpectedTags)
Checks a set of tags for matching parameters.private void
checkReturnTag(List<JavadocTag> tags, int lineNo, boolean reportExpectedTags)
Checks for only one return tag.private void
checkThrowsTags(List<JavadocTag> tags, List<JavadocMethodCheck.ExceptionInfo> throwsList, boolean reportExpectedTags)
Checks a set of tags for matching throws.private static List<JavadocMethodCheck.ExceptionInfo>
combineExceptionInfo(Collection<JavadocMethodCheck.ExceptionInfo> first, Iterable<JavadocMethodCheck.ExceptionInfo> second)
Combine ExceptionInfo collections together by matching names.static List<DetailAST>
findTokensInAstByType(DetailAST root, int astType)
Finds node of specified type among root children, siblings, siblings children on any deep level.int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.private static JavadocMethodCheck.ExceptionInfo
getExceptionInfo(DetailAST ast)
Get ExceptionInfo instance.private static DetailAST
getFirstClassNameNode(DetailAST ast)
Get node where class name of exception starts.private static List<JavadocTag>
getMethodTags(TextBlock comment)
Returns the tags in a javadoc comment.private static List<JavadocTag>
getMultilineNoArgTags(Matcher noargMultilineStart, String[] lines, int lineIndex, int tagLine)
Gets multiline Javadoc tags with no arguments.private static List<DetailAST>
getParameters(DetailAST ast)
Computes the parameter nodes for a method.int[]
getRequiredTokens()
The tokens that this check must be registered for.private static List<JavadocMethodCheck.ExceptionInfo>
getThrowed(DetailAST methodAst)
Get ExceptionInfo for all exceptions that throws in method code by 'throw new'.private static List<JavadocMethodCheck.ExceptionInfo>
getThrows(DetailAST ast)
Computes the exception nodes for a method.private boolean
hasShortCircuitTag(DetailAST ast, List<JavadocTag> tags)
Validates whether the Javadoc has a short circuit tag.private static boolean
isClassNamesSame(String class1, String class2)
Check that class names are same by short name of class.private static boolean
isExceptionInfoSame(JavadocMethodCheck.ExceptionInfo info1, JavadocMethodCheck.ExceptionInfo info2)
Check that ExceptionInfo objects are same by name.private static boolean
isInIgnoreBlock(DetailAST methodBodyAst, DetailAST throwAst)
Checks if a 'throw' usage is contained within a block that should be ignored.private void
processAST(DetailAST ast)
Called to process an AST when visiting it.private static void
processThrows(Iterable<JavadocMethodCheck.ExceptionInfo> throwsIterable, String documentedClassName)
Verifies that documented exception is in throws.private static boolean
removeMatchingParam(Iterable<DetailAST> params, String paramName)
Remove parameter from params collection by name.private static boolean
searchMatchingTypeParameter(Iterable<DetailAST> typeParams, String requiredTypeName)
Returns true if required type found in type parameters.void
setAccessModifiers(AccessModifierOption... accessModifiers)
Setter to specify the access modifiers where Javadoc comments are checked.void
setAllowedAnnotations(String... userAnnotations)
Setter to specify annotations that allow missed documentation.void
setAllowMissingParamTags(boolean flag)
Setter to control whether to ignore violations when a method has parameters but does not have matchingparam
tags in the javadoc.void
setAllowMissingReturnTag(boolean flag)
Setter to control whether to ignore violations when a method returns non-void type and does not have areturn
tag in the javadoc.void
setValidateThrows(boolean value)
Setter to control whether to validatethrows
tags.private boolean
shouldCheck(DetailAST ast)
Whether we should check this node.void
visitToken(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, 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_CLASS_INFO
public static final String MSG_CLASS_INFO
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_UNUSED_TAG_GENERAL
public static final String MSG_UNUSED_TAG_GENERAL
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_INVALID_INHERIT_DOC
public static final String MSG_INVALID_INHERIT_DOC
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_UNUSED_TAG
public static final String MSG_UNUSED_TAG
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_EXPECTED_TAG
public static final String MSG_EXPECTED_TAG
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_RETURN_EXPECTED
public static final String MSG_RETURN_EXPECTED
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
MSG_DUPLICATE_TAG
public static final String MSG_DUPLICATE_TAG
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
ELEMENT_START
private static final String ELEMENT_START
Html element start symbol.- See Also:
- Constant Field Values
-
ELEMENT_END
private static final String ELEMENT_END
Html element end symbol.- See Also:
- Constant Field Values
-
MATCH_JAVADOC_ARG
private static final Pattern MATCH_JAVADOC_ARG
Compiled regexp to match Javadoc tags that take an argument.
-
MATCH_JAVADOC_ARG_MISSING_DESCRIPTION
private static final Pattern MATCH_JAVADOC_ARG_MISSING_DESCRIPTION
Compiled regexp to match Javadoc tags with argument but with missing description.
-
MATCH_JAVADOC_MULTILINE_CONT
private static final Pattern MATCH_JAVADOC_MULTILINE_CONT
Compiled regexp to look for a continuation of the comment.
-
END_JAVADOC
private static final String END_JAVADOC
Multiline finished at end of comment.- See Also:
- Constant Field Values
-
NEXT_TAG
private static final String NEXT_TAG
Multiline finished at next Javadoc.- See Also:
- Constant Field Values
-
MATCH_JAVADOC_NOARG
private static final Pattern MATCH_JAVADOC_NOARG
Compiled regexp to match Javadoc tags with no argument.
-
MATCH_JAVADOC_NOARG_MULTILINE_START
private static final Pattern MATCH_JAVADOC_NOARG_MULTILINE_START
Compiled regexp to match first part of multilineJavadoc tags.
-
MATCH_JAVADOC_NOARG_CURLY
private static final Pattern MATCH_JAVADOC_NOARG_CURLY
Compiled regexp to match Javadoc tags with no argument and {}.
-
accessModifiers
private AccessModifierOption[] accessModifiers
Specify the access modifiers where Javadoc comments are checked.
-
validateThrows
private boolean validateThrows
Control whether to validatethrows
tags.
-
allowMissingParamTags
private boolean allowMissingParamTags
Control whether to ignore violations when a method has parameters but does not have matchingparam
tags in the javadoc.
-
allowMissingReturnTag
private boolean allowMissingReturnTag
Control whether to ignore violations when a method returns non-void type and does not have areturn
tag in the javadoc.
-
allowedAnnotations
private Set<String> allowedAnnotations
Specify annotations that allow missed documentation.
-
-
Constructor Detail
-
JavadocMethodCheck
public JavadocMethodCheck()
-
-
Method Detail
-
setValidateThrows
public void setValidateThrows(boolean value)
Setter to control whether to validatethrows
tags.- Parameters:
value
- user's value.- Since:
- 6.0
-
setAllowedAnnotations
public void setAllowedAnnotations(String... userAnnotations)
Setter to specify annotations that allow missed documentation.- Parameters:
userAnnotations
- user's value.- Since:
- 6.0
-
setAccessModifiers
public void setAccessModifiers(AccessModifierOption... accessModifiers)
Setter to specify the access modifiers where Javadoc comments are checked.- Parameters:
accessModifiers
- access modifiers.- Since:
- 8.42
-
setAllowMissingParamTags
public void setAllowMissingParamTags(boolean flag)
Setter to control whether to ignore violations when a method has parameters but does not have matchingparam
tags in the javadoc.- Parameters:
flag
- aBoolean
value- Since:
- 3.1
-
setAllowMissingReturnTag
public void setAllowMissingReturnTag(boolean flag)
Setter to control whether to ignore violations when a method returns non-void type and does not have areturn
tag in the javadoc.- Parameters:
flag
- aBoolean
value- Since:
- 3.1
-
getRequiredTokens
public final 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
-
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
-
visitToken
public final void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
processAST
private void processAST(DetailAST ast)
Called to process an AST when visiting it.- Parameters:
ast
- the AST to process. Guaranteed to not be PACKAGE_DEF or IMPORT tokens.
-
shouldCheck
private boolean shouldCheck(DetailAST ast)
Whether we should check this node.- Parameters:
ast
- a given node.- Returns:
- whether we should check a given node.
-
checkComment
private void checkComment(DetailAST ast, TextBlock comment)
Checks the Javadoc for a method.- Parameters:
ast
- the token for the methodcomment
- the Javadoc comment
-
hasShortCircuitTag
private boolean hasShortCircuitTag(DetailAST ast, List<JavadocTag> tags)
Validates whether the Javadoc has a short circuit tag. Currently, this is the inheritTag. Any violations are logged.- Parameters:
ast
- the construct being checkedtags
- the list of Javadoc tags associated with the construct- Returns:
- true if the construct has a short circuit tag.
-
getMethodTags
private static List<JavadocTag> getMethodTags(TextBlock comment)
Returns the tags in a javadoc comment. Only finds throws, exception, param, return and see tags.- Parameters:
comment
- the Javadoc comment- Returns:
- the tags found
-
calculateTagColumn
private static int calculateTagColumn(MatchResult javadocTagMatchResult, int lineNumber, int startColumnNumber)
Calculates column number using Javadoc tag matcher.- Parameters:
javadocTagMatchResult
- found javadoc tag match resultlineNumber
- line number of Javadoc tag in commentstartColumnNumber
- column number of Javadoc comment beginning- Returns:
- column number
-
getMultilineNoArgTags
private static List<JavadocTag> getMultilineNoArgTags(Matcher noargMultilineStart, String[] lines, int lineIndex, int tagLine)
Gets multiline Javadoc tags with no arguments.- Parameters:
noargMultilineStart
- javadoc tag Matcherlines
- comment text lineslineIndex
- line number that contains the javadoc tagtagLine
- javadoc tag line number in file- Returns:
- javadoc tags with no arguments
-
getParameters
private static List<DetailAST> getParameters(DetailAST ast)
Computes the parameter nodes for a method.- Parameters:
ast
- the method node.- Returns:
- the list of parameter nodes for ast.
-
getThrows
private static List<JavadocMethodCheck.ExceptionInfo> getThrows(DetailAST ast)
Computes the exception nodes for a method.- Parameters:
ast
- the method node.- Returns:
- the list of exception nodes for ast.
-
getThrowed
private static List<JavadocMethodCheck.ExceptionInfo> getThrowed(DetailAST methodAst)
Get ExceptionInfo for all exceptions that throws in method code by 'throw new'.- Parameters:
methodAst
- method DetailAST object where to find exceptions- Returns:
- list of ExceptionInfo
-
getExceptionInfo
private static JavadocMethodCheck.ExceptionInfo getExceptionInfo(DetailAST ast)
Get ExceptionInfo instance.- Parameters:
ast
- DetailAST object where to find exceptions node;- Returns:
- ExceptionInfo
-
getFirstClassNameNode
private static DetailAST getFirstClassNameNode(DetailAST ast)
Get node where class name of exception starts.- Parameters:
ast
- DetailAST object where to find exceptions node;- Returns:
- exception node where class name starts
-
isInIgnoreBlock
private static boolean isInIgnoreBlock(DetailAST methodBodyAst, DetailAST throwAst)
Checks if a 'throw' usage is contained within a block that should be ignored. Such blocks consist of try (with catch) blocks, local classes, anonymous classes, and lambda expressions. Note that a try block without catch is not considered.- Parameters:
methodBodyAst
- DetailAST node representing the method bodythrowAst
- DetailAST node representing the 'throw' literal- Returns:
- true if throwAst is inside a block that should be ignored
-
combineExceptionInfo
private static List<JavadocMethodCheck.ExceptionInfo> combineExceptionInfo(Collection<JavadocMethodCheck.ExceptionInfo> first, Iterable<JavadocMethodCheck.ExceptionInfo> second)
Combine ExceptionInfo collections together by matching names.- Parameters:
first
- the first collection of ExceptionInfosecond
- the second collection of ExceptionInfo- Returns:
- combined list of ExceptionInfo
-
findTokensInAstByType
public static List<DetailAST> findTokensInAstByType(DetailAST root, int astType)
Finds node of specified type among root children, siblings, siblings children on any deep level.
-
checkParamTags
private void checkParamTags(List<JavadocTag> tags, DetailAST parent, boolean reportExpectedTags)
Checks a set of tags for matching parameters.- Parameters:
tags
- the tags to checkparent
- the node which takes the parametersreportExpectedTags
- whether we should report if do not find expected tag
-
searchMatchingTypeParameter
private static boolean searchMatchingTypeParameter(Iterable<DetailAST> typeParams, String requiredTypeName)
Returns true if required type found in type parameters.- Parameters:
typeParams
- collection of type parametersrequiredTypeName
- name of required type- Returns:
- true if required type found in type parameters.
-
removeMatchingParam
private static boolean removeMatchingParam(Iterable<DetailAST> params, String paramName)
Remove parameter from params collection by name.- Parameters:
params
- collection of DetailAST parametersparamName
- name of parameter- Returns:
- true if parameter found and removed
-
checkReturnTag
private void checkReturnTag(List<JavadocTag> tags, int lineNo, boolean reportExpectedTags)
Checks for only one return tag. All return tags will be removed from the supplied list.- Parameters:
tags
- the tags to checklineNo
- the line number of the expected tagreportExpectedTags
- whether we should report if do not find expected tag
-
checkThrowsTags
private void checkThrowsTags(List<JavadocTag> tags, List<JavadocMethodCheck.ExceptionInfo> throwsList, boolean reportExpectedTags)
Checks a set of tags for matching throws.- Parameters:
tags
- the tags to checkthrowsList
- the throws to checkreportExpectedTags
- whether we should report if do not find expected tag
-
processThrows
private static void processThrows(Iterable<JavadocMethodCheck.ExceptionInfo> throwsIterable, String documentedClassName)
Verifies that documented exception is in throws.- Parameters:
throwsIterable
- collection of throwsdocumentedClassName
- documented exception class name
-
isExceptionInfoSame
private static boolean isExceptionInfoSame(JavadocMethodCheck.ExceptionInfo info1, JavadocMethodCheck.ExceptionInfo info2)
Check that ExceptionInfo objects are same by name.- Parameters:
info1
- ExceptionInfo objectinfo2
- ExceptionInfo object- Returns:
- true is ExceptionInfo object have the same name
-
isClassNamesSame
private static boolean isClassNamesSame(String class1, String class2)
Check that class names are same by short name of class. If some class name is fully qualified it is cut to short name.- Parameters:
class1
- class nameclass2
- class name- Returns:
- true is ExceptionInfo object have the same name
-
-