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 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 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 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"/>
     

    Example:

     public class Test {
    
      /**
       *
       */
      Test(int x) {            // violation, param tag missing for x
      }
    
      /**
       *
       */
      public int foo(int p1) { // violation, param tag missing for p1
        return p1;             // violation, return tag missing
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // violation, return tag missing
      }
    
      /**
       *
       */
      void bar(int p1) {       // violation, param tag missing for p1
      }                        // ok, no return tag for void method
     }
     

    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>
     

    Example:

     public class Test {
    
      /**
       *
       */
      Test(int x) {            // ok, only public methods checked
      }
    
      /**
       *
       */
      public int foo(int p1) { // ok, missing param tags allowed
        return p1;             // violation, return tag missing
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // ok, only public methods checked
      }
    
      /**
       *
       */
      void bar(int p1) {       // ok, missing param tags allowed
      }                        // ok, no return tag for void method
     }
     

    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>
     

    Example:

     class Test {
    
      /**
       *
       */
      Test(int x) {            // violation, param tag missing for x
      }
    
      /**
       *
       */
      public int foo(int p1) { // ok, public methods not checked
        return p1;
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // violation, return tag missing
      }
    
      /**
       *
       */
      void bar(int p1) {       // violation, param tag missing for p1
      }                        // ok, no return tag for void method
     }
     

    To configure the check to ignore any missing return tags:

     <module name="JavadocMethod">
       <property name="allowMissingReturnTag" value="true"/>
     </module>
     

    Example:

     public class Test {
    
      /**
       *
       */
      Test(int x) {            // violation, param tag missing for x
      }
    
      /**
       *
       */
      public int foo(int p1) { // violation, param tag missing for p1
        return p1;             // ok, missing return tag allowed
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // ok, missing return tag allowed
      }
    
      /**
       *
       */
      void bar(int p1) {       // violation, param tag missing for p1
      }                        // ok, no return tag for void method
     }
     

    To configure the check to ignore Methods with annotation Deprecated:

     <module name="JavadocMethod">
       <property name="allowedAnnotations" value="Deprecated"/>
     </module>
     

    Example:

     public class Test {
    
      /**
       *
       */
      Test(int x) {            // violation, param tag missing for x
      }
    
      /**
       *
       */
      public int foo(int p1) { // violation, param tag missing for p1
        return p1;             // violation, return tag missing
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // ok, Deprecated methods not checked
      }
    
      /**
       *
       */
      void bar(int p1) {       // violation, param tag missing for p1
      }                        // ok, no return tag for void method
     }
     

    To configure the check only for tokens which are Constructor Definitions:

     <module name="JavadocMethod">
       <property name="tokens" value="CTOR_DEF"/>
     </module>
     

    Example:

     public class Test {
    
      /**
       *
       */
      Test(int x) {            // violation, param tag missing for x
      }
    
      /**
       *
       */
      public int foo(int p1) { // ok, method not checked
        return p1;             // ok, method not checked
      }
    
      /**
       *
       * @param p1 The first number
       */
      @Deprecated
      private int boo(int p1) {
        return p1;             // ok, method not checked
      }
    
      /**
       *
       */
      void bar(int p1) {       // ok, method not checked
      }
     }
     

    To configure the check to validate throws tags, you can use following config.

     <module name="JavadocMethod">
       <property name="validateThrows" value="true"/>
     </module>
     

    Example:

     /**
      * 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
    Since:
    3.0
    • Field Detail

      • MSG_CLASS_INFO

        public static final java.lang.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

        public static final java.lang.String MSG_UNUSED_TAG
        A key is pointing to the warning message text in "messages.properties" file.
        See Also:
        Constant Field Values
      • MATCH_JAVADOC_ARG

        private static final java.util.regex.Pattern MATCH_JAVADOC_ARG
        Compiled regexp to match Javadoc tags that take an argument.
      • MATCH_JAVADOC_ARG_MISSING_DESCRIPTION

        private static final java.util.regex.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 java.util.regex.Pattern MATCH_JAVADOC_MULTILINE_CONT
        Compiled regexp to look for a continuation of the comment.
      • MATCH_JAVADOC_NOARG

        private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG
        Compiled regexp to match Javadoc tags with no argument.
      • MATCH_JAVADOC_NOARG_MULTILINE_START

        private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG_MULTILINE_START
        Compiled regexp to match first part of multilineJavadoc tags.
      • MATCH_JAVADOC_NOARG_CURLY

        private static final java.util.regex.Pattern MATCH_JAVADOC_NOARG_CURLY
        Compiled regexp to match Javadoc tags with no argument and {}.
      • currentClassName

        private java.lang.String currentClassName
        Name of current class.
      • validateThrows

        private boolean validateThrows
        Control whether to validate throws tags.
      • allowMissingParamTags

        private boolean allowMissingParamTags
        Control whether to ignore violations when a method has parameters but does not have matching param tags in the javadoc.
      • allowMissingReturnTag

        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.
      • allowedAnnotations

        private java.util.Set<java.lang.String> allowedAnnotations
        Specify annotations that allow missed documentation.
    • Method Detail

      • setValidateThrows

        public void setValidateThrows​(boolean value)
        Setter to control whether to validate throws tags.
        Parameters:
        value - user's value.
      • setAllowedAnnotations

        public void setAllowedAnnotations​(java.lang.String... userAnnotations)
        Setter to specify annotations that allow missed documentation.
        Parameters:
        userAnnotations - user's value.
      • setAccessModifiers

        public void setAccessModifiers​(AccessModifierOption... accessModifiers)
        Setter to specify the access modifiers where Javadoc comments are checked.
        Parameters:
        accessModifiers - access modifiers.
      • 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
      • 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
      • 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
      • beginTree

        public void beginTree​(DetailAST rootAST)
        Description copied from class: AbstractCheck
        Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.
        Overrides:
        beginTree in class AbstractCheck
        Parameters:
        rootAST - the root of the tree
      • 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,
                                           java.util.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 java.util.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​(java.util.regex.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 java.util.List<JavadocTaggetMultilineNoArgTags​(java.util.regex.Matcher noargMultilineStart,
                                                                        java.lang.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 java.util.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 java.util.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 java.util.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​(java.util.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​(java.lang.Iterable<DetailAST> typeParams,
                                                           java.lang.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​(java.lang.Iterable<DetailAST> params,
                                                   java.lang.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​(java.util.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​(java.util.List<JavadocTag> tags,
                                     java.util.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​(java.lang.Iterable<JavadocMethodCheck.ExceptionInfo> throwsIterable,
                                          JavadocMethodCheck.ClassInfo documentedClassInfo,
                                          java.util.Set<java.lang.String> foundThrows)
        Verifies that documented exception is in throws.
        Parameters:
        throwsIterable - collection of throws
        documentedClassInfo - documented exception class info
        foundThrows - previously found throws
      • isClassNamesSame

        private static boolean isClassNamesSame​(java.lang.String class1,
                                                java.lang.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
      • processClass

        private void processClass​(DetailAST ast)
        Processes class definition.
        Parameters:
        ast - class definition to process.