2011-12-14 78 views
23

我需要知道如何在運行時讀Javadoc註釋如何通過反射閱讀Javadoc評論?

說我有以下功能(可能是反射?):

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

    //... 
} 

在運行時,我能得到這個功能多的信息通過反思..但不能讀取評論。所以問題是,如何在運行時閱讀這個javadoc評論。

+0

由於這裏的2名回答說,他們不能用做編譯後的代碼,你應該可以使用源代碼。爲了做到這一點,請嘗試搜索「從源代碼提取javadoc」,然後獲取一些開源工具並根據需要對其進行修改。 – 2011-12-14 12:06:39

+0

我認爲使用@Puce更容易,因爲我是源代碼的所有者! – 2011-12-14 12:41:22

回答

14

考慮使用註釋代替Javadoc並編寫註釋處理器。

16

你不能。他們從編譯後的代碼中被刪除。

7

你不能那樣做,因爲javadoc沒有被編譯到最終的類中。

30

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