DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Increase Your Code Quality in Java by Exploring the Power of Javadoc
  • Documentation Debt Is the Real Risk in Long-Lived Network Infrastructure
  • Build Software Faster With Three Simple Principles
  • When Your Documentation Manages Itself: mdship and AI-Assisted Markdown

Trending

  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • The SDLC After AI
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Extracting Javadoc Documentation From Source Files Using JavaParser

Extracting Javadoc Documentation From Source Files Using JavaParser

JavaParser can give you a quick hand manipulating your AST and finding Javadoc comments. It can't return them in a structured way (yet), but it's still a time saver.

By 
Federico Tomassetti
·
Jan. 13, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

A lot of people are using JavaParser for a lot of different goals. One of these is extracting documentation. In this short post, we will see how you can print all the Javadoc comments associated to classes or interfaces.

If you want to jump in, the code is available on GitHub.

Getting All the Javadoc Comments for Classes

We are reusing DirExplorer, a supporting class presented in the introduction to JavaParser. This class permits us to process a directory, recursively, parsing all the Java files contained there.

We can start by iterating over all the classes and finding the associated Javadoc comments.

/**
 * Iterate over the classes and print their Javadoc.
 */
public class ClassesJavadocExtractor {

    public static void main(String[] args) {
        File projectDir = new File("source_to_parse/");
        new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {
            try {
                new VoidVisitorAdapter<Object>() {
                    @Override
                    public void visit(ClassOrInterfaceDeclaration n, Object arg) {
                        super.visit(n, arg);
                        if (n.getComment() != null && n.getComment() instanceof JavadocComment) {
                            String title = String.format("%s (%s)", n.getName(), path);
                            System.out.println(title);
                            System.out.println(Strings.repeat("=", title.length()));
                            System.out.println(n.getComment());
                        }
                    }
                }.visit(JavaParser.parse(file), null);
            } catch (IOException e) {
                new RuntimeException(e);
            }
        }).explore(projectDir);
    }

}


As you can see, getting the Javadoc comments is fairly easy. It produces this result:

ASTParserConstants (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParserConstants.java)
==============================================================================================================================
/**
 * Token literal values and constants.
 * Generated by org.javacc.parser.OtherFilesGen#start()
 */

ParseException (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ParseException.java)
======================================================================================================================
/**
 * This exception is thrown when parse errors are encountered.
 * You can explicitly create objects of this exception type by
 * calling the method generateParseException in the generated
 * parser.
 *
 * You can modify this class to customize your error reporting
 * mechanisms so long as you retain the public fields.
 */

ASTParser (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParser.java)
============================================================================================================
/**
 * <p>This class was generated automatically by javacc, do not edit.</p>
 */

ASTParserTokenManager (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParserTokenManager.java)
====================================================================================================================================
/** Token Manager. */


Getting All the Javadoc Comments and Finding the Documented Elements

In other cases, we may want to start collecting all the JavaDoc comments and then finding the element that is commented. We can also do that easily with JavaParser:

/**
 * Iterate over all the Javadoc comments and print them together with a description of the commented element.
 */
public class AllJavadocExtractor {

    public static void main(String[] args) {
        File projectDir = new File("source_to_parse/");
        new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {
            try {
                new VoidVisitorAdapter<Object>() {
                    @Override
                    public void visit(JavadocComment comment, Object arg) {
                        super.visit(comment, arg);
                        String title = null;
                        if (comment.getCommentedNode().isPresent()) {
                            title = String.format("%s (%s)", describe(comment.getCommentedNode().get()), path);
                        } else {
                            title = String.format("No element associated (%s)", path);
                        }
                        System.out.println(title);
                        System.out.println(Strings.repeat("=", title.length()));
                        System.out.println(comment);
                    }
                }.visit(JavaParser.parse(file), null);
            } catch (IOException e) {
                new RuntimeException(e);
            }
        }).explore(projectDir);
    }

    private static String describe(Node node) {
        if (node instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration)node;
            return "Method " + methodDeclaration.getDeclarationAsString();
        }
        if (node instanceof ConstructorDeclaration) {
            ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration)node;
            return "Constructor " + constructorDeclaration.getDeclarationAsString();
        }
        if (node instanceof ClassOrInterfaceDeclaration) {
            ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)node;
            if (classOrInterfaceDeclaration.isInterface()) {
                return "Interface " + classOrInterfaceDeclaration.getName();
            } else {
                return "Class " + classOrInterfaceDeclaration.getName();
            }
        }
        if (node instanceof EnumDeclaration) {
            EnumDeclaration enumDeclaration = (EnumDeclaration)node;
            return "Enum " + enumDeclaration.getName();
        }
        if (node instanceof FieldDeclaration) {
            FieldDeclaration fieldDeclaration = (FieldDeclaration)node;
            List<String> varNames = fieldDeclaration.getVariables().stream().map(v -> v.getName().getId()).collect(Collectors.toList());
            return "Field " + String.join(", ", varNames);
        }
        return node.toString();
    }

}


Here, most of the code is about providing a description for the commented node (method describe).

Conclusions

Manipulating the AST and finding the Javadoc comments is quite easy. However, one missing feature is the possibility to extract the information contained in the Javadoc in a structured form. For example, you may want to get only the part of the Javadoc with a certain parameter or to the return value. Javaparser currently does not have this feature, but I am working on it, and it should be merged in the next weeks or two. If you want to follow the development take a look at issue 433.

Thanks for reading and happy parsing!

Javadoc Documentation

Published at DZone with permission of Federico Tomassetti. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Increase Your Code Quality in Java by Exploring the Power of Javadoc
  • Documentation Debt Is the Real Risk in Long-Lived Network Infrastructure
  • Build Software Faster With Three Simple Principles
  • When Your Documentation Manages Itself: mdship and AI-Assisted Markdown

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook