如何通过反射阅读Javadoc注释?

时间:2011-12-14 11:53:17

标签: java reflection runtime javadoc

我需要知道如何在运行时阅读Javadoc注释(可能是通过反射?)

说我有以下功能:

/**
*  function that do some thing
*/
public void myFunc()
{

    //...
}

在运行时,我可以通过反射获得有关此函数的更多信息。但无法读取注释。所以问题是,如何在运行时阅读 javadoc 注释。

4 个答案:

答案 0 :(得分:31)

Doclet上课:

public class ExtractCommentsDoclet {
    public static boolean start(RootDoc root) throws IOException {
        for (ClassDoc c : root.classes()) {
            print(c.qualifiedName(), c.commentText());
            for (FieldDoc f : c.fields(false)) {
                print(f.qualifiedName(), f.commentText());
            }
            for (MethodDoc m : c.methods(false)) {
                print(m.qualifiedName(), m.commentText());
                if (m.commentText() != null && m.commentText().length() > 0) {
                    for (ParamTag p : m.paramTags())
                        print(m.qualifiedName() + "@" + p.parameterName(), p.parameterComment());
                    for (Tag t : m.tags("return")) {
                        if (t.text() != null && t.text().length() > 0)
                            print(m.qualifiedName() + "@return", t.text());
                    }
                }
            }
        }
        return true;
    }

    private static void print(String name, String comment) throws IOException {
        if (comment != null && comment.length() > 0) {
            new FileWriter(name + ".txt").append(comment).close();
        }
    }
}

maven执行:

<plugin>
    <artifactId>maven-javadoc-plugin</artifactId>
    <extensions>true</extensions>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>aggregate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <doclet>ExtractCommentsDoclet</doclet>
        <docletPath>${project.build.directory}/classes</docletPath>
        <reportOutputDirectory>${project.build.outputDirectory}/META-INF</reportOutputDirectory>
        <useStandardDocletOptions>false</useStandardDocletOptions>
    </configuration>
</plugin>

从类路径中读取文档:META-INF / apidocs

答案 1 :(得分:19)

你做不到。它们已从已编译的代码中删除。

答案 2 :(得分:15)

考虑使用注释而不是Javadoc并编写注释处理器。

答案 3 :(得分:7)

你不能这样做,因为javadoc没有编译成最终的类。

相关问题