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 by throw new in the method body), but for which no throws tag is
present by activation of property validateThrows.
Note that throw new is not checked in the following places:
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)
allowedAnnotations - Specify the list of annotations
that allow missed documentation.
Type is java.lang.String[].
Default value is Override.
validateThrows - Control whether to validate throws tags.
Type is boolean.
Default value is false.
accessModifiers - Specify the access modifiers where Javadoc comments are
checked.
Type is com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption[].
Default value is public, protected, package, private.
allowMissingParamTags - Control whether to ignore violations
when a method has parameters but does not have matching param tags in the javadoc.
Type is boolean.
Default value is false.
allowMissingReturnTag - Control whether to ignore violations
when a method returns non-void type and does not have a return tag in the javadoc.
Type is boolean.
Default value is false.
tokens - tokens to check
Type is java.lang.String[].
Validation type is tokenSet.
Default value is:
METHOD_DEF,
CTOR_DEF,
ANNOTATION_FIELD_DEF,
COMPACT_CTOR_DEF.
To configure the default check:
<module name="JavadocMethod"/>
To configure the check for only public modifier, ignoring any missing param tags is:
<module name="JavadocMethod"> <property name="accessModifiers" value="public"/> <property name="allowMissingParamTags" value="true"/> </module>
To configure the check for methods which are in private and package,
but not any other modifier:
<module name="JavadocMethod"> <property name="accessModifiers" value="private, package"/> </module>
To configure the check to validate throws tags, you can use following config.
<module name="JavadocMethod"> <property name="validateThrows" value="true"/> </module>
/**
* Actual exception thrown is child class of class that is declared in throws.
* It is limitation of checkstyle (as checkstyle does not know type hierarchy).
* Javadoc is valid not declaring FileNotFoundException
* BUT checkstyle can not distinguish relationship between exceptions.
* @param file some file
* @throws IOException if some problem
*/
public void doSomething8(File file) throws IOException {
if (file == null) {
throw new FileNotFoundException(); // violation
}
}
/**
* Exact throw type referencing in javadoc even first is parent of second type.
* It is a limitation of checkstyle (as checkstyle does not know type hierarchy).
* This javadoc is valid for checkstyle and for javadoc tool.
* @param file some file
* @throws IOException if some problem
* @throws FileNotFoundException if file is not found
*/
public void doSomething9(File file) throws IOException {
if (file == null) {
throw new FileNotFoundException();
}
}
/**
* Ignore try block, but keep catch and finally blocks.
*
* @param s String to parse
* @return A positive integer
*/
public int parsePositiveInt(String s) {
try {
int value = Integer.parseInt(s);
if (value <= 0) {
throw new NumberFormatException(value + " is negative/zero"); // ok, try
}
return value;
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid number", ex); // violation, catch
} finally {
throw new IllegalStateException("Should never reach here"); // violation, finally
}
}
/**
* Try block without catch is not ignored.
*
* @return a String from standard input, if there is one
*/
public String readLine() {
try (Scanner sc = new Scanner(System.in)) {
if (!sc.hasNext()) {
throw new IllegalStateException("Empty input"); // violation, not caught
}
return sc.next();
}
}
/**
* Lambda expressions are ignored as we do not know when the exception will be thrown.
*
* @param s a String to be printed at some point in the future
* @return a Runnable to be executed when the string is to be printed
*/
public Runnable printLater(String s) {
return () -> {
if (s == null) {
throw new NullPointerException(); // ok
}
System.out.println(s);
};
}
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
| Modifier and Type | Class and Description |
|---|---|
private static class |
JavadocMethodCheck.ClassInfo
Contains class's
Token. |
private static class |
JavadocMethodCheck.ExceptionInfo
Stores useful information about declared exception.
|
private static class |
JavadocMethodCheck.Token
Represents text element with location in the text.
|
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private AccessModifierOption[] |
accessModifiers
Specify the access modifiers where Javadoc comments are checked.
|
private java.util.List<java.lang.String> |
allowedAnnotations
Specify the list of annotations that allow missed documentation.
|
private boolean |
allowMissingParamTags
Control whether to ignore violations when a method has parameters but does
not have matching
param tags in the javadoc. |
private boolean |
allowMissingReturnTag
Control whether to ignore violations when a method returns non-void type
and does not have a
return tag in the javadoc. |
private java.lang.String |
currentClassName
Name of current class.
|
private static java.lang.String |
END_JAVADOC
Multiline finished at end of comment.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_ARG
Compiled regexp to match Javadoc tags that take an argument.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_ARG_MISSING_DESCRIPTION
Compiled regexp to match Javadoc tags with argument but with missing description.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_MULTILINE_CONT
Compiled regexp to look for a continuation of the comment.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_NOARG
Compiled regexp to match Javadoc tags with no argument.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_NOARG_CURLY
Compiled regexp to match Javadoc tags with no argument and {}.
|
private static java.util.regex.Pattern |
MATCH_JAVADOC_NOARG_MULTILINE_START
Compiled regexp to match first part of multilineJavadoc tags.
|
static java.lang.String |
MSG_CLASS_INFO
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_DUPLICATE_TAG
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_EXPECTED_TAG
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_INVALID_INHERIT_DOC
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_RETURN_EXPECTED
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_UNUSED_TAG
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_UNUSED_TAG_GENERAL
A key is pointing to the warning message text in "messages.properties"
file.
|
private static java.lang.String |
NEXT_TAG
Multiline finished at next Javadoc.
|
private boolean |
validateThrows
Control whether to validate
throws tags. |
| Constructor and Description |
|---|
JavadocMethodCheck() |
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(DetailAST rootAST)
Called before the starting to process a tree.
|
private static int |
calculateTagColumn(java.util.regex.Matcher javadocTagMatcher,
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(java.util.List<JavadocTag> tags,
DetailAST parent,
boolean reportExpectedTags)
Checks a set of tags for matching parameters.
|
private void |
checkReturnTag(java.util.List<JavadocTag> tags,
int lineNo,
boolean reportExpectedTags)
Checks for only one return tag.
|
private void |
checkThrowsTags(java.util.List<JavadocTag> tags,
java.util.List<JavadocMethodCheck.ExceptionInfo> throwsList,
boolean reportExpectedTags)
Checks a set of tags for matching throws.
|
private static java.util.List<JavadocMethodCheck.ExceptionInfo> |
combineExceptionInfo(java.util.List<JavadocMethodCheck.ExceptionInfo> list1,
java.util.List<JavadocMethodCheck.ExceptionInfo> list2)
Combine ExceptionInfo lists together by matching names.
|
static java.util.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 java.util.List<JavadocTag> |
getMethodTags(TextBlock comment)
Returns the tags in a javadoc comment.
|
private static java.util.List<JavadocTag> |
getMultilineNoArgTags(java.util.regex.Matcher noargMultilineStart,
java.lang.String[] lines,
int lineIndex,
int tagLine)
Gets multiline Javadoc tags with no arguments.
|
private static java.util.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 java.util.List<JavadocMethodCheck.ExceptionInfo> |
getThrowed(DetailAST methodAst)
Get ExceptionInfo for all exceptions that throws in method code by 'throw new'.
|
private static java.util.List<JavadocMethodCheck.ExceptionInfo> |
getThrows(DetailAST ast)
Computes the exception nodes for a method.
|
private boolean |
hasShortCircuitTag(DetailAST ast,
java.util.List<JavadocTag> tags)
Validates whether the Javadoc has a short circuit tag.
|
private static boolean |
isClassNamesSame(java.lang.String class1,
java.lang.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.
|
void |
leaveToken(DetailAST ast)
Called after all the child nodes have been process.
|
private void |
processAST(DetailAST ast)
Called to process an AST when visiting it.
|
private void |
processClass(DetailAST ast)
Processes class definition.
|
private static void |
processThrows(java.util.List<JavadocMethodCheck.ExceptionInfo> throwsList,
JavadocMethodCheck.ClassInfo documentedClassInfo,
java.util.Set<java.lang.String> foundThrows)
Verifies that documented exception is in throws.
|
private static boolean |
removeMatchingParam(java.util.List<DetailAST> params,
java.lang.String paramName)
Remove parameter from params collection by name.
|
private static boolean |
searchMatchingTypeParameter(java.util.List<DetailAST> typeParams,
java.lang.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(java.lang.String... userAnnotations)
Setter to specify the list of 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 matching
param 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 a
return tag in the javadoc. |
void |
setValidateThrows(boolean value)
Setter to control whether to validate
throws tags. |
private boolean |
shouldCheck(DetailAST ast)
Whether we should check this node.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_CLASS_INFO
public static final java.lang.String MSG_UNUSED_TAG_GENERAL
public static final java.lang.String MSG_INVALID_INHERIT_DOC
public static final java.lang.String MSG_UNUSED_TAG
public static final java.lang.String MSG_EXPECTED_TAG
public static final java.lang.String MSG_RETURN_EXPECTED
public static final java.lang.String MSG_DUPLICATE_TAG
private static final java.util.regex.Pattern MATCH_JAVADOC_ARG
private static final java.util.regex.Pattern MATCH_JAVADOC_ARG_MISSING_DESCRIPTION
private static final java.util.regex.Pattern MATCH_JAVADOC_MULTILINE_CONT
private static final java.lang.String END_JAVADOC
private static final java.lang.String NEXT_TAG
private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG
private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG_MULTILINE_START
private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG_CURLY
private java.lang.String currentClassName
private AccessModifierOption[] accessModifiers
private boolean validateThrows
throws tags.private boolean allowMissingParamTags
param tags in the javadoc.private boolean allowMissingReturnTag
return tag in the javadoc.private java.util.List<java.lang.String> allowedAnnotations
public JavadocMethodCheck()
public void setValidateThrows(boolean value)
throws tags.value - user's value.public void setAllowedAnnotations(java.lang.String... userAnnotations)
userAnnotations - user's value.public void setAccessModifiers(AccessModifierOption... accessModifiers)
accessModifiers - access modifiers.public void setAllowMissingParamTags(boolean flag)
param tags in the javadoc.flag - a Boolean valuepublic void setAllowMissingReturnTag(boolean flag)
return tag in the javadoc.flag - a Boolean valuepublic final int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic void beginTree(DetailAST rootAST)
AbstractCheckbeginTree in class AbstractCheckrootAST - the root of the treepublic final void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processpublic final void leaveToken(DetailAST ast)
AbstractCheckleaveToken in class AbstractCheckast - the token leavingprivate void processAST(DetailAST ast)
ast - the AST to process. Guaranteed to not be PACKAGE_DEF or
IMPORT tokens.private boolean shouldCheck(DetailAST ast)
ast - a given node.private void checkComment(DetailAST ast, TextBlock comment)
ast - the token for the methodcomment - the Javadoc commentprivate boolean hasShortCircuitTag(DetailAST ast, java.util.List<JavadocTag> tags)
ast - the construct being checkedtags - the list of Javadoc tags associated with the constructprivate static java.util.List<JavadocTag> getMethodTags(TextBlock comment)
comment - the Javadoc commentprivate static int calculateTagColumn(java.util.regex.Matcher javadocTagMatcher, int lineNumber, int startColumnNumber)
javadocTagMatcher - found javadoc tag matcherlineNumber - line number of Javadoc tag in commentstartColumnNumber - column number of Javadoc comment beginningprivate static java.util.List<JavadocTag> getMultilineNoArgTags(java.util.regex.Matcher noargMultilineStart, java.lang.String[] lines, int lineIndex, int tagLine)
noargMultilineStart - javadoc tag Matcherlines - comment text lineslineIndex - line number that contains the javadoc tagtagLine - javadoc tag line number in fileprivate static java.util.List<DetailAST> getParameters(DetailAST ast)
ast - the method node.private static java.util.List<JavadocMethodCheck.ExceptionInfo> getThrows(DetailAST ast)
ast - the method node.private static java.util.List<JavadocMethodCheck.ExceptionInfo> getThrowed(DetailAST methodAst)
methodAst - method DetailAST object where to find exceptionsprivate static JavadocMethodCheck.ExceptionInfo getExceptionInfo(DetailAST ast)
ast - DetailAST object where to find exceptions node;private static DetailAST getFirstClassNameNode(DetailAST ast)
ast - DetailAST object where to find exceptions node;private static boolean isInIgnoreBlock(DetailAST methodBodyAst, DetailAST throwAst)
methodBodyAst - DetailAST node representing the method bodythrowAst - DetailAST node representing the 'throw' literalprivate static java.util.List<JavadocMethodCheck.ExceptionInfo> combineExceptionInfo(java.util.List<JavadocMethodCheck.ExceptionInfo> list1, java.util.List<JavadocMethodCheck.ExceptionInfo> list2)
list1 - list of ExceptionInfolist2 - list of ExceptionInfopublic static java.util.List<DetailAST> findTokensInAstByType(DetailAST root, int astType)
root - DetailASTastType - value of TokenTypeList of DetailAST nodes which matches the predicate.private void checkParamTags(java.util.List<JavadocTag> tags, DetailAST parent, boolean reportExpectedTags)
tags - the tags to checkparent - the node which takes the parametersreportExpectedTags - whether we should report if do not find
expected tagprivate static boolean searchMatchingTypeParameter(java.util.List<DetailAST> typeParams, java.lang.String requiredTypeName)
typeParams - list of type parametersrequiredTypeName - name of required typeprivate static boolean removeMatchingParam(java.util.List<DetailAST> params, java.lang.String paramName)
params - collection of DetailAST parametersparamName - name of parameterprivate void checkReturnTag(java.util.List<JavadocTag> tags, int lineNo, boolean reportExpectedTags)
tags - the tags to checklineNo - the line number of the expected tagreportExpectedTags - whether we should report if do not find
expected tagprivate void checkThrowsTags(java.util.List<JavadocTag> tags, java.util.List<JavadocMethodCheck.ExceptionInfo> throwsList, boolean reportExpectedTags)
tags - the tags to checkthrowsList - the throws to checkreportExpectedTags - whether we should report if do not find
expected tagprivate static void processThrows(java.util.List<JavadocMethodCheck.ExceptionInfo> throwsList, JavadocMethodCheck.ClassInfo documentedClassInfo, java.util.Set<java.lang.String> foundThrows)
throwsList - list of throwsdocumentedClassInfo - documented exception class infofoundThrows - previously found throwsprivate static boolean isExceptionInfoSame(JavadocMethodCheck.ExceptionInfo info1, JavadocMethodCheck.ExceptionInfo info2)
info1 - ExceptionInfo objectinfo2 - ExceptionInfo objectprivate static boolean isClassNamesSame(java.lang.String class1, java.lang.String class2)
class1 - class nameclass2 - class nameprivate void processClass(DetailAST ast)
ast - class definition to process.Copyright © 2001-2022. All Rights Reserved.