4.10. Java API ドキュメントのコードスニペット
Red Hat build of OpenJDK 21 には、Javadoc ツールの標準ドックレット用の @snippet
タグが含まれています。@snippet
タグは、API ドキュメントへのソースコードのサンプルの追加を簡素化するのに役立ちます。
以下に例を示します。
/** * The following code shows how to use {@code Optional.isPresent}: * {@snippet : * if (v.isPresent()) { * System.out.println("v: " + v.get()); // @highlight substring="println" * } * } */
/**
* The following code shows how to use {@code Optional.isPresent}:
* {@snippet :
* if (v.isPresent()) {
* System.out.println("v: " + v.get()); // @highlight substring="println"
* }
* }
*/
マークアップタグ
@snippet
タグを @highlight
などのマークアップタグと組み合わせて使用して、コードのスタイルを変更できます。たとえば、次のコードスニペットでは、@highlight
タグを使用して、API ドキュメント内の println
メソッド名を強調表示します。
/** * The following code shows how to use {@code Optional.isPresent}: * {@snippet : * if (v.isPresent()) { * System.out.println("v: " + v.get()); // @highlight substring="println" * } * } */
/**
* The following code shows how to use {@code Optional.isPresent}:
* {@snippet :
* if (v.isPresent()) {
* System.out.println("v: " + v.get()); // @highlight substring="println"
* }
* }
*/
外部ファイル
@snippet
タグを、ソースコードを含む外部ファイルと組み合わせて使用することもできます。
以下に例を示します。
/** * The following code shows how to use {@code Optional.isPresent}: * {@snippet file="ShowOptional.java" region="example"} */
/**
* The following code shows how to use {@code Optional.isPresent}:
* {@snippet file="ShowOptional.java" region="example"}
*/
上記の例では、ShowOptional.java
は次のコードを含むファイルです。
public class ShowOptional { void show(Optional<String> v) { // @start region="example" if (v.isPresent()) { System.out.println("v: " + v.get()); } // @end } }
public class ShowOptional {
void show(Optional<String> v) {
// @start region="example"
if (v.isPresent()) {
System.out.println("v: " + v.get());
}
// @end
}
}
外部コードの場所は、class
属性を使用してクラス名として指定することも、file
属性を使用して相対ファイルパスとして指定することもできます。
詳細は、JEP 413: Code Snippets in Java API Documentation を参照してください。