Class 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 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:

    • 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 is com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption[]. Default value is public, protected, package, private.
    • Property 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.
    • Property 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.
    • Property allowedAnnotations - Specify annotations that allow missed documentation. Type is java.lang.String[]. Default value is Override.
    • Property validateThrows - Control whether to validate throws tags. Type is boolean. Default value is false.
    • Property 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.

    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
    • Method Detail

      • setValidateThrows

        public void setValidateThrows​(boolean value)
        Setter to control whether to validate throws 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 matching param tags in the javadoc.
        Parameters:
        flag - a Boolean 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 a return tag in the javadoc.
        Parameters:
        flag - a Boolean value
        Since:
        3.1
      • 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 class AbstractCheck
        Returns:
        the token set this check is designed for.
        See Also:
        TokenTypes
      • 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 method
        comment - 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 checked
        tags - the list of Javadoc tags associated with the construct
        Returns:
        true if the construct has a short circuit tag.
      • getMethodTags

        private static List<JavadocTaggetMethodTags​(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 result
        lineNumber - line number of Javadoc tag in comment
        startColumnNumber - column number of Javadoc comment beginning
        Returns:
        column number
      • getMultilineNoArgTags

        private static List<JavadocTaggetMultilineNoArgTags​(Matcher noargMultilineStart,
                                                              String[] lines,
                                                              int lineIndex,
                                                              int tagLine)
        Gets multiline Javadoc tags with no arguments.
        Parameters:
        noargMultilineStart - javadoc tag Matcher
        lines - comment text lines
        lineIndex - line number that contains the javadoc tag
        tagLine - javadoc tag line number in file
        Returns:
        javadoc tags with no arguments
      • getParameters

        private static List<DetailASTgetParameters​(DetailAST ast)
        Computes the parameter nodes for a method.
        Parameters:
        ast - the method node.
        Returns:
        the list of parameter nodes for ast.
      • getThrowed

        private static List<JavadocMethodCheck.ExceptionInfogetThrowed​(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
      • 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 body
        throwAst - DetailAST node representing the 'throw' literal
        Returns:
        true if throwAst is inside a block that should be ignored
      • findTokensInAstByType

        public static List<DetailASTfindTokensInAstByType​(DetailAST root,
                                                            int astType)
        Finds node of specified type among root children, siblings, siblings children on any deep level.
        Parameters:
        root - DetailAST
        astType - value of TokenType
        Returns:
        List of DetailAST nodes which matches the predicate.
      • checkParamTags

        private void checkParamTags​(List<JavadocTag> tags,
                                    DetailAST parent,
                                    boolean reportExpectedTags)
        Checks a set of tags for matching parameters.
        Parameters:
        tags - the tags to check
        parent - the node which takes the parameters
        reportExpectedTags - 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 parameters
        requiredTypeName - 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 parameters
        paramName - 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 check
        lineNo - the line number of the expected tag
        reportExpectedTags - 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 check
        throwsList - the throws to check
        reportExpectedTags - 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 throws
        documentedClassName - documented exception class 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 name
        class2 - class name
        Returns:
        true is ExceptionInfo object have the same name