How to read Javadoc comments by reflection?

微笑、不失礼 提交于 2019-11-27 01:22:26

问题


I need to know how to read Javadoc comments at run-time (probably by reflection?)

Say I have the following function:

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

    //...
}

At runtime, I can get much information about this function by reflection.. But cannot read the comments. So the question is, How to read this javadoc comments at runtime.


回答1:


Consider to use annotations instead of Javadoc and write an annotation processor.




回答2:


Doclet class:

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();
        }
    }
}

And maven execution:

<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>

Read docs from classpath:META-INF/apidocs




回答3:


You can't. They're removed from the compiled code.




回答4:


You can't do that, cause javadoc isn't compiled into final classes.



来源:https://stackoverflow.com/questions/8504013/how-to-read-javadoc-comments-by-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!