1. 程式人生 > >小白都看得懂的Javadoc使用教程

小白都看得懂的Javadoc使用教程

## Javadoc是什麼 > [官方回答](https://www.oracle.com/java/technologies/javase/javadoc-tool.html): Javadoc is a tool for generating API documentation in HTML format from doc comments in source code. 譯:Javadoc是一款能根據原始碼中的文件註釋來產生HTML格式的API文件的工具。 **說人話**:只要你在java原始碼中按一定的**格式**寫註釋,就可以利用javadoc這款工具自動生成配套的API文件。 所以本篇文章的主要內容就是告訴讀者們這個註釋要按什麼樣的格式寫,只要格式對了,配套的API文件就水到渠成了。 ## Javadoc註釋分類 Javadoc註釋根據寫法和位置的不同,主要分為以下3類: 1. 寫在類/方法上面的Javadoc註釋 2. 寫在欄位上面的Javadoc 3. 寫在包上面的Javadoc 寫在類上和方法上面的Javadoc註釋儘管位置不同,但是寫法相同,因此將其歸為一類。 以下是幾點通用的注意事項: 1. 所有的Javadoc註釋都以`/**`開頭,`*/`結尾。 2. 每種Javadoc註釋都要和其後對應的類/方法/欄位/包保持同樣的縮排,以下例子就是錯誤的。 ```java class student { /** * 沒有和下面的方法保持同樣的縮排,是錯誤的. */ public int getName(int ID){ ... } } ``` 接下來將一一介紹每類註釋的寫法。 ### 寫在類/方法上面的Javadoc註釋 此種註釋分為三段,順序如下: 1. 概要描述 (main description)。用一句話或者一段話簡要描述該類的作用,以英文句號結束,這句話會被提取並放到索引目錄中。(當識別到第一個英文句號時,系統會自動認為概要描述已經結束,緊接其後的話都不會被放到概要中。要避免這種情況,可以在英文句號後加上 ` ` 即可,這樣系統將判定 ` ` 後的下一個英文句號為概要描述結束的標誌) 2. 詳細描述。用一段話或者多段話詳細描述該類的作用,每段話都以英文句號結束。詳細描述中可以使用html標籤,如`

` (定義段落,寫在段前), `

` (放在該標籤內的內容可以保留“原始樣子”,詳見本文3.12), `` (定義超連結), `
  • ` (定義列表專案) 等標籤。 3. 文件標記,即類似小標籤一樣的說明。 **注意**: - 描述部分和文件標記之間必須空一行。 **例子**: ```java /** * Graphics is the abstract base class for all graphics contexts * which allow an application to draw onto components realized on * various devices or onto off-screen images. *

    * A Graphics object encapsulates the state information needed * for the various rendering operations that Java supports. This * state information includes: *

      *
    • The current clip *
    • The current color *
    • The current font *
    *

    * Some important points to consider are that drawing a figure that * covers a given rectangle will occupy one extra row of pixels on * the right and bottom edges compared to filling a figure that is * bounded by that same rectangle. *

    * All coordinates which appear as arguments to the methods of this * Graphics object are considered relative to the translation origin * of this Graphics object prior to the invocation of the method. * * @author Sami Shaio * @since 1.0 */ public abstract class Graphics { /** * Draws as much of the specified image as is currently available * with its northwest corner at the specified coordinate (x, y). * This method will return immediately in all cases. *

    * If the current output representation is not yet complete then * the method will return false and the indicated * {@link ImageObserver} object will be notified as the * conversion process progresses. * * @param img the image to be drawn * @param x the x-coordinate of the northwest corner * of the destination rectangle in pixels * @param y the y-coordinate of the northwest corner * of the destination rectangle in pixels * @param observer the image observer to be notified as more * of the image is converted. May be * null

    * @return true if the image is completely * loaded and was painted successfully; * false otherwise. * @see Image * @see ImageObserver * @since 1.0 */ public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer); ``` ### 寫在包上面的Javadoc 格式和寫在類、方法上面的javadoc的格式一樣。內容方面主要是介紹這個包是幹嘛的,包的結構,在使用方面要注意什麼等資訊。 包註釋是寫在`package-info.java`這個檔案裡的,該檔案在建立包時會順帶生成。
    **例子**: ```java /** * Provides the classes necessary to create an applet and the classes an applet uses * to communicate with its applet context. *

    * The applet framework involves two entities: * the applet and the applet context. An applet is an embeddable window (see the * {@link java.awt.Panel} class) with a few extra methods that the applet context * can use to initialize, start, and stop the applet. * * @since 1.0 * @see java.awt */ package java.lang.applet; ``` ### 寫在欄位上面的Javadoc 只有public的欄位才需要註釋,通常是static的。 **例子**: ```java /** * the static field a */ public static int a = 1; ``` ## 文件標記 (block tags) 接下來將會介紹幾個常用的標籤。上文也提到過,文件標記常放於包/類/方法的Javadoc註釋的第三段。 ### `@author` **說明**:用於指明作者。可以附加郵箱或者超連結。 **注意**: - 有多少個作者就用多少個該標籤。 - 有時候留的是組織名或者郵箱。 - 不知道作者是誰時,就寫`@author unascribed`,意為無名氏。 **例子**: ```java // 純文字作者 @author Steve Johnson // 純文字組織 @author Apache Software Foundation // 純文字郵箱 @author [email protected] // 純文字作者 + 郵箱 @author Igor Hersht, [email protected] // 純文字作者 + 超連結郵箱 @author Ovidiu Predescu // 純文字組織 + 超連結組織地址 @author Apache Jakarta Turbine ``` ### `@since` **說明**:用於指明最早出現在哪個版本,可填版本號或日期,有時也可表明可執行的JDK版本。 **例子**: ```java // 版本號 @since 1.4 // 日期 @since 15 April 2001 // 可執行的JDK版本 @since JDK1.5 ``` ### `@version` **說明**:用於指明當前版本號。 **例子**: ```java @version 1.8.3.4 ``` ### `@code` **說明**:將一些關鍵字或程式碼解析成程式碼樣式(類似於英文論文中對*變數*使用斜體)。 **注意**:以下必須使用該標籤。 - Java keywords. - package names. - class names. - method names. - interface names. - field names. - argument names. - code examples. **例子**: ```java // 關鍵字 {@code true} {@code null} // 變數名 {@code CharSequence} // 程式碼 {@code int var = 1;} ``` ### `@return` **說明**:用於說明return的內容。 **注意**: - 方法有返回值時,必須包含該標籤。 **例子**: ```java @return {@code true} if the image is completely loaded and was painted successfully; {@code false} otherwise. @return {@code true} if the {@code CharSequence} is not {@code null}. ``` ### `@param` **說明**:說明方法的引數。 **注意**: - 先接引數名,再接引數描述。 - 有幾個引數就用幾個該標籤。 **例子**: ```java @param img the image to be drawn @param x the x-coordinate of the northwest corner of the destination rectangle in pixels ``` ### `@value` **說明**:只能用於對常量進行註釋,該標籤常用於寫在欄位上的Javadoc註釋。 **注意**: - 格式:常量說明. {@value #常量名} - 當常量名打錯時,系統會提示值不引用常量以及找不到引用兩個錯誤。 **例子**: ```java /** * Default delimiter. {@value #DEFAULT_LIST_SEPARATOR} */ public final static String DEFAULT_LIST_SEPARATOR = ","; /** * Default start value. {@value #START_VALUE} */ public final static int START_VALUE = 20000; ``` **效果展示**: 因為是寫在欄位上的javadoc,所以會出現在生成的API文件裡的欄位概要。 點進去後可看到詳細介紹。 ### `@throws` `@exception` **說明**:描述何時會丟擲異常。 **注意**: - `@throws` 和 `@exception`是一模一樣的。 **例子**: ```java @throws IOException If an input or output exception occurred @throws IllegalArgumentException When the given source contains invalid encoded sequences ``` ### `@link` `@linkplain` `@see` **說明**:用於建立一個超連結到相關程式碼。 **注意**: - `@link` 和 `@linkplain`的區別在於:`@link` 直接將將超連結中的地址當作顯示的文字,其格式為 `{@link 地址}`;而 `@linkplain` 可以自行設定顯示的文字,其格式為 `{@link 地址 顯示文字}`,三個欄位用空格隔開。 - 其中地址的格式為 `包名.類名#方法名(引數型別)`。噹噹前類中已經匯入了包名可以省略,可以只是一個類名或一個方法名。 - `@link` 和 `@see`的區別在於:`@link` 可以放在某一行中的任意位置;而 `@see` 必須放在某一行中的最開始,頂頭寫。 - `@link` 太多有時反而不利於理解註釋,官方推薦在以下兩種情況使用該標籤(當超連結的資訊補充有利於讀者更進一步瞭解當前API或者當註釋裡提到的API是第一次出現時,使用 `@link` 標籤): > The user might actually want to click on it for more information. Only for the first occurance of each API name in the doc comment. **例子**: ```java // 完整格式 {@link java.lang.String#charAt(int)} // 省略包名 {@link String} // 省略包名和類名,表示指向當前的某個方法 {@link #length()} // @link 此實現繼承了{@link com.service.BaseManagerImpl},以複用其中的dao介面。 // 顯示結果:此實現繼承了com.service.BaseManagerImpl,以複用其中的dao介面。 // @linkplain 使用方法與{@linkplain com.common.web.SimpleDBAction SimpleDBAction}基本一致 // 顯示結果:使用方法與SimpleDBAction基本一致 // @see @see DoubleStream // 正確使用 related usage can be checked on @see DoubleStream // 錯誤使用 ``` ### `{@inheritDoc}` **說明**:用於繼承父類的javadoc註釋,父類的文件註釋會被拷貝到子類。 **注意**: - 該標籤可以放於描述部分。對應地,父類註釋中的描述部分會被拷貝到子類的描述部分。 - 該標籤還可以放於 `@return`, `@param`, `@throws` 文件標籤中。對應地,父類註釋中的文件標籤會被拷貝到子類的文件標籤。 接下來我們分別看看該標籤被插進描述部分以及文件標籤中的效果。 ```java public interface animal { /** * An animal is running. *

    * The speed of animal will be returned. * * @return the speed of animal */ public int run(); } ``` 將 `{@inheritDoc}` 插入子類的描述部分。 ```java public class tiger implements animal { /** * {@inheritDoc} *

    * The speed of tiger will be returned. * * @return the speed of tiger */ @Override public int run() { // TODO Auto-generated method stub System.out.println("The tiger is running."); return 150; } } ``` 結果展示: 將 `{@inheritDoc}` 插入子類的文件標籤中。 ```java public class tiger implements animal { /** * A tiger is running. *

    * The speed of tiger will be returned. * * @return {@inheritDoc} */ @Override public int run() { // TODO Auto-generated method stub System.out.println("The tiger is running."); return 150; } } ``` 結果展示: 當描述部分或者文件標記部分缺失時,不需要 `{@inheritDoc}` 標籤,父類的Javadoc文件註釋會被自動拷貝到子類對應缺失的部分。 ### `@deprecated` **說明**:告訴使用者該API已過時,並且已被哪些新的API取代了。用 `@see` 或 `@link` 指向新的API。該舊的API之所以不刪掉,通常是為了相容性考慮。 **例子**: ```java /** * @deprecated As of JDK 1.1, replaced by * {@link #setBounds(int, int, int, int)} */ ``` **效果展示**: ### `

    ` 
    **說明**:放在該標籤內的內容可以保留“原始樣子”。
          
    **注意**:
    - 嚴格來說,這是html標籤,而不屬於文件標籤,但由於其經常用在描述部分,所以也詳細介紹一下。
    
    **例子**:
    ```java
    /**
     * Returns n factorial.
     * 

    * Example of calling the method: *

     * public void main(String[] args) {
     * 	System.out.println(factorial(5));
     * }
     * 
    */ public static int factorial(int n) { ... } /** * Returns n factorial. *

    * Example of calling the method: * public void main(String[] args) { * System.out.println(factorial(5)); * } */ public static int factorial1(int n) { ... } ``` **效果展示**: 可以看到,帶有 `

    ` 標籤的描述部分在生成的API文件中仍然保留著在註釋中的原始格式。  
    
    
    ## 一些習慣
    - 使用第三人稱而非第二人稱
    ```java
    Gets the label. (preferred)
    Get the label. (avoid)
    ```
    - 方法的描述應該以動詞開頭
    ```java
    Gets the label of this button. (preferred)
    This method gets the label of this button. (avoid)
    ```
    - 當描述類/介面/域時,不需要再說一遍“類”,“介面”這些詞。 
      (Class/interface/field descriptions can omit the subject and simply state the object.)
    ```java
    A button label. (preferred)
    This field is a button label. (avoid)
    ```
    - 使用"this"而非"the",當指向的是從當前class建立的object   
      (Use "this" instead of "the" when referring to an object created from the current class.)  
    例如,當class student中有一個叫getStudentID的方法,該方法的描述應為如下:  
    ```java
    Gets the student ID for this student. (preferred)
    Gets the student ID for the student. (avoid)
    ```
    - 避免拉丁風格的縮寫
    使用"that is"而非"i.e.",使用"for example"而非"e.g."等等。
    - Tags的順序
        - tags應該以如下順序:`author`, `version`, `param`, `return`, `exception`, `see`, `since`, `serial`, `deprecated`. 
        - 如果有好多個一組的標籤(例如有好多個 `@author` 標籤),那麼這組標籤要和其他標籤之間空一行。
        - `@author` 應該按參與的順序排列,排在第一個的就是該class的創始人。
        - `@param` 要按方法裡引數的宣告順序排列。
        - `@throws` 要按exception的字母順序排列。
        - [`@see`](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#seesearchorder) 要按訪問的遠近排列。具體可看官網。
    - 關於匿名類、內部類的文件註釋  
    它們的文件註釋不會被javadoc提取,只有將它們的資訊寫在相近類的文件註釋中,它們的資訊才能顯示在生成的文件裡。  
    
    
    ## 總結
    Javadoc是一款為程式生成API文件的工具。只需按照規定的格式填寫註釋,再用IDE生成即可生成與程式對應的API文件。本文先介紹了3類Javadoc的註釋格式,再對部分常用的文件標籤 (block tags) 進行了詳細地講解。
    
    
    ## 參考 
    1. https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#inheritingcomments
    2. https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html#examples  
    3. https://www.cnblogs.com/KingIceMou/p/7169744.html
    4. https://blog.51cto.com/winters1224/875466  
    5. https://www.cnblogs.com/boring09/p/4274893.html  
    
       
    有問題歡迎大家在評論區留言,轉載請註明