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 the list of 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"/>
     

    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
    Since:
    3.0
    • 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​(String... userAnnotations)
        Setter to specify the list of 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,
                                           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​(Matcher javadocTagMatcher,
                                              int lineNumber,
                                              int startColumnNumber)
        Calculates column number using Javadoc tag matcher.
        Parameters:
        javadocTagMatcher - found javadoc tag matcher
        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​(List<DetailAST> typeParams,
                                                           String requiredTypeName)
        Returns true if required type found in type parameters.
        Parameters:
        typeParams - list of type parameters
        requiredTypeName - name of required type
        Returns:
        true if required type found in type parameters.
      • removeMatchingParam

        private static boolean removeMatchingParam​(List<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
      • 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
      • processClass

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