有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

假设我有以下功能:

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

    //...
}

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


共 (4) 个答案

  1. # 1 楼答案

    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

  2. # 2 楼答案

    考虑使用注释代替JavaDoc并编写注释处理器。

  3. # 3 楼答案

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

  4. # 4 楼答案

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