Javadoc源文件解析 [英] Javadoc source file parsing
问题描述
在我的程序中,我动态获取.java文件的名称。在这个文件中我需要找到所有方法,foreach方法也是所有参数(也有它们的注释)。
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).
我通读了这里的讨论,发现这个 https://code.google.com/p/javaparser/ javaparser,看起来很容易使用,但问题是,它只是1.5。
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.
比你提到的,Java 1.6已经有了内置的解析器(javax.lang.model)。但我无法弄清楚它是如何运作的。你知道它的任何好的教程/例子吗?
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?
你知道解析java源文件的其他方法吗?
Do you know any other way to parse java source file?
推荐答案
如何使用 Doclet API ?
通常,此API用于bat文件,但您可以通过以下方式以编程方式调用。
How about using Doclet API?
Normally, This API is used from bat file, but you can invoke programmatically like the following.
重要:此API不存在于rt.jar(JRE)中,而是存在于tools.jar(JDK)中。所以你需要将tool.jar添加到类路径中。
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;
}
}
}
这篇关于Javadoc源文件解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!