Javadoc source file parsing

2019-02-15 05:28发布

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?

标签: java parsing
2条回答
狗以群分
2楼-- · 2019-02-15 06:23

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;
        }
    }
}
查看更多
家丑人穷心不美
3楼-- · 2019-02-15 06:34

Take another look at the javaparser project. It has been updated to support all modern Java versions.

The Doclet API is really hard to use and is badly documented. It will be either going away or be replaced with something better, hopefully even in Java 1.9.

查看更多
登录 后发表回答