java - 如何通过反射读取 Javadoc 注释?

标签 java reflection runtime javadoc

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

假设我有以下功能:

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

    //...
}

在运行时,我可以通过反射得到很多关于这个函数的信息。但是看不到评论。所以问题是,如何在运行时阅读此 javadoc 注释。

最佳答案

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

关于java - 如何通过反射读取 Javadoc 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504013/

相关文章:

Java:在这里包含一个 else 更快吗?还是更好的练习?

java - 对象镜像其他对象

go - 如何调用 golang struct 字段的函数?

java - 没有枚举的状态模式和 hibernate

java - 以编程方式从特定位置运行脚本

java - 进程 p = Runtime.getRuntime().exec() 将异步运行?

java - Sns @NotificationMessage 不适用于 String 以外的类型

java - 无法使用 java api 连接到 Hbase

java - 通过字段名称获取对象引用

java - HashMap和LinkedHashMap中插入数据后如何计算内存中的大小?