Javadoc source file parsing

java, parsing

Solution

How about using Doclet API? Normally, This API is used from bat file, but you can invoke programmatically like the following.

IMPORTANT: This API exists in not rt.jar(JRE) but tools.jar (JDK). So you need to add tool.jar into classpath.

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doclet;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.javadoc.Main;

public class DocletTest {

    public static void main(String[] args) {
        Main.execute("", Analyzer.class.getName(), new String[] {"path/to/your/file.java"});
    }

    public static class Analyzer extends Doclet {

        public static boolean start(RootDoc root) {
            for (ClassDoc classDoc : root.classes()) {
                System.out.println("Class: " + classDoc.qualifiedName());

                for (MethodDoc methodDoc : classDoc.methods()) {
                    System.out.println("  " + methodDoc.returnType() + " " + methodDoc.name() + methodDoc.signature());
                }
            }
            return false;
        }
    }
}

Problem

in my program I dynamically get the name of the .java file. In this file I need to find all methods, foreach method also all parameters (also with their annotations). I read through the discussions here and found this https://code.google.com/p/javaparser/ javaparser, that seems pretty easy to use, but the problem is, that it is just for 1.5. Than you mentioned, that Java 1.6 has already got built-in parser (javax.lang.model). But I can not figure out, how it works. Do you know any good tutorial/example of it? Do you know any other way to parse java source file?

Original source