Java 文档注释

javadoc 标签、文档注释写法与生成 HTML 文档。

Beginner
Key Points文档注释写在声明之前,用 /** */;@param/@return/@throws 描述契约,javadoc 命令生成 HTML。

javadoc 标签

Common tags: @param for parameters, @return for the result, @throws for exceptions, @author, @since, @see for related links and @deprecated for retired APIs.

TagUsed onMeaning
@param name descmethod / constructorDescribe a parameter
@return descmethodDescribe the return value
@throws Type whymethodDescribe a thrown exception
@author nameclass / interfaceAuthor
@since versionanySince which version
@deprecatedanyMark as obsolete

文档注释的写法

The first sentence is the summary shown in method lists, so state what it does in one line. A blank line separates details. HTML tags like <p> and <code> are allowed.

Java
/**
 * 数值计算工具。
 *
 * <p>所有方法都是无状态的静态方法,可安全并发调用。
 *
 * @author BackendWiki
 * @since 1.0
 */
public class SquareNum {

    /**
     * 返回参数的平方。
     *
     * @param num 待计算的整数
     * @return {@code num * num}
     */
    public static int square(int num) {
        return num * num;
    }

    /**
     * 整数除法。
     *
     * @param a 被除数
     * @param b 除数,不能为 0
     * @return 商
     * @throws ArithmeticException 当 {@code b == 0}
     */
    public static int div(int a, int b) {
        return a / b;
    }

    public static void main(String[] args) {
        System.out.println(square(4));
        System.out.println(div(6, 3));
    }
}
Output
16
2

javadoc 输出什么

javadoc -d doc src/*.java writes a full HTML site under doc/: class index, method summary and per-method detail. That is exactly what Ctrl+Q shows in the IDE.

Text
$ javadoc -d doc -encoding UTF-8 -charset UTF-8 SquareNum.java

正在生成 doc/SquareNum.html ...
正在构建所有类和包的所有方法索引 ...
A mismatched @param or @return only warns; the build continues. Add -Xwerror in CI to fail instead, keeping docs in sync with code.

Friends & Partners