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

Muh*_*edy 28 java reflection javadoc runtime

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

说我有以下功能:

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

    //...
}
Run Code Online (Sandbox Code Playgroud)

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

小智 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和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>
Run Code Online (Sandbox Code Playgroud)

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


Tho*_*mas 19

你不能.它们已从编译的代码中删除.


Puc*_*uce 15

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


4nd*_*rew 7

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