Code Snippets in Java API Documentation – Java API 文档中的代码片段

最后修改: 2023年 9月 29日

中文/混合/英文(键盘快捷键:t)

 1. Overview

1.概述

Comprehensive documentation helps developers work with libraries easily. Javadoc is a great tool that helps generate documentation for Java code. Java 18 introduced the @snippet tag to easily integrate code snippets into documentation.

全面的文档可帮助开发人员轻松使用库。Javadoc是一款有助于为 Java 代码生成文档的优秀工具。Java 18 引入了 @snippet 标记,可轻松将代码片段集成到文档中

In this tutorial, we’ll explore how to add code snippets into documentation using the @snippet tag.

在本教程中,我们将探讨如何使用 @snippet 标记将代码片段添加到文档中。

2. Before the @snippet Tag

2.在 @snippet 标记之前

Before Java 18, we could add code snippets in documentation using the @code tag. However, this came with some limitations.

在 Java 18 之前,我们可以使用 @code 标记在文档中添加代码片段。不过,这也有一些限制。

The @code tag treats the code like normal text. It doesn’t validate code snippets and highlight syntax.

@code标记将代码视为普通文本。它不会验证代码片段和高亮显示语法

3. Using the @snippet Tag

3.使用 @snippet 标记

Java 18 introduced the @snippet tag to address the limitations of the @code tag. It has features to highlight code syntax.

Java 18 引入了 @snippet 标记,以解决 @code 标记的局限性。它具有突出显示代码语法的功能。

Further, it makes it easy to embed code in documentation. It also comes with features to add code from external sources to documentation.

此外,它还可以轻松地在文档中嵌入代码它还具有将外部来源的代码添加到文档中的功能

Additionally, code fragments can be validated using the Compiler Tree APIs.

此外,还可使用编译树 API 验证代码片段。

The @snippet tag can be used in two different ways – in-line snippet and external code snippet.

@snippet 标记有两种不同的使用方式–内联代码片段和外部代码片段

3.1. In-Line Code Snippets

3.1 行内代码片段

The in-line code snippets help to add code snippets to a Javadoc comment by explicitly putting the code within the @snippet tag.

内联代码片段通过将代码明确置于 @snippet 标记中,有助于将代码片段添加到 Javadoc 注释中

The @snippet tag has opening and closing curly braces. The code snippets are written after the colon sign. Additionally, the code snippets must be within the curly braces:

@snippet 标记有开头和结尾大括号。代码片段写在冒号之后。此外,代码片段必须位于大括号内:

{@snippet : "placeholder for code snippets" }

Here’s an example of documentation using the in-line code snippets:

下面是一个使用内联代码片段编写文档的示例:

/**
 * The code below shows the content of {@code helloBaeldung()} method
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung");
 * }
 * }
 */
public class GreetingsInlineSnippet {
    public void helloBaeldung() {
        System.out.println("Hello From Team Baeldung");
    }
}

In the above code, we add the helloBaeldung() method in the documentation. First, we define the @snippet tag. Then, we write the code snippet within the tag.

在上述代码中,我们在文档中添加了 helloBaeldung() 方法。首先,我们定义 @snippet 标记。然后,我们在标记中编写代码片段。

Here’s the generated  Javadoc:an-in-line-snippet-to-show-hello-baeldung-method

以下是生成的 Javadoc:an-in-line-snippet-to-show-hello-baeldung-method <a href=”/wp-content/uploads/2023/09/an-in-line-snippet-to-show-hello-baeldung-method-2.

The above image shows an in-line code snippet embedded in documentation.

上图显示的是嵌入到文档中的内联代码片段。

3.2. External Code Snippets

3.2 外部代码片段

Additionally, we can add to documentation code snippets from an external file or a class. First, we have to specify the region we want to add using the @start and @end tags.

此外,我们还可以在文档中添加来自外部文件或类的代码片段。首先,我们必须使用 @start@end 标记指定要添加的区域

Let’s write some simple documentation that shows a method to implement binary search in Java.

让我们编写一些简单的文档,展示在 Java 中实现二进制搜索的方法。

First, let’s create a class named BinarySearch with a method to implement binary search and specify the portion to add to the documentation:

首先,让我们创建一个名为 BinarySearch 的类,其中包含一个实现二进制搜索的方法,并指定要添加到文档中的部分:

public class BinarySearch {
    public int search(int[] list, int item) {
        int index = Integer.MAX_VALUE;
        int low = 0;
        int high = list.length - 1;
        
        // @start region="binary"
        while (low <= high) { 
            int mid = high - low; 
            int guess = list[mid]; 
            if (guess == item) { 
                index = mid; break; 
            } else if (guess > item) {
                low = mid - 1;
            } else {
                low = mid + 1;
            }
            low++;
        }
        // @end region="binary"
        return index;
    }
}

In the code above, we want to add the region named “binary” to documentation in the GreetingsExternalSnippet class. We use the @start tag to mark the start region and the @end tag to mark the end region.

在上面的代码中,我们希望在 GreetingsExternalSnippet 类中的文档中添加名为”二进制“的区域。我们使用 @start 标记来标记起始区域,使用 @end 标记来标记结束区域。

Furthermore, binary” is a unique name for the marked region, and it can be used to call the section in any Javadoc.

此外,二进制“是标记区域的唯一名称,可用于在任何 Javadoc 中调用该部分

Let’s add the code to a Javadoc comment in a GreetingsExternalSnippet class:

让我们将代码添加到 GreetingsExternalSnippet 类中的 Javadoc 注释中:

/**
 * 
 * External code snippet showing the loop process in binary search method.
 * {@snippet class="BinarySearch" region="binary"}
 */
  
public class GreetingsExternalSnippet {
    public void helloBinarySearch() {
        System.out.println("Hi, it's great knowing that binary search uses a loop under the hood");
    }
}

Here, we call an external file using the @snippet tag by giving the correct class name and the region name. Also, we need to place the external classes or files in a directory named snippet-files for the Javadoc command to recognize the path of the external file or class.

在这里,我们使用 @snippet 标记调用外部文件,并给出正确的类名和区域名。此外,我们还需要将外部类或文件放到名为 snippet-files 的目录中,以便 Javadoc 命令识别外部文件或类的路径

To generate the Javadoc, we need to specify the folder snippet-files with the –snippet-path option to avoid errors while generating the documentation:

要生成 Javadoc,我们需要使用 -snippet-path 选项指定 snippet-files 文件夹,以避免在生成文档时出错

$ javadoc -d doc com.baeldung.snippettag --snippet-path snippet-files

The command above generates the documentation.

上述命令将生成文档。

Here’s the generated Javadoc:external-snippet-tag-showing-while-loop-in-binary-search

以下是生成的 Javadoc:external-snippet-tag-showing-while-loop-in-binary-search <a href=”/wp-content/uploads/2023/09/external-snippet-tag-showing-while-loop-in-binary-search-2.

The section named binary is successfully imported into the documentation.

名为 binary 的部分已成功导入到文档中。

Notably, we can also import snippets from files like properties files, config files, etc., using the file attributes.

值得注意的是,我们还可以使用文件属性从属性文件、配置文件等文件中导入片段。

Here’s an example that shows a properties file with a defined region:

下面的示例显示了一个定义了区域的属性文件:

# @start region="zone"
local.timezone = GMT+1
local.zip = 94123
# @end region="zone"

Next, let’s embed the defined “zone” in a Javadoc comment by using the file attribute:

接下来,让我们使用 file 属性,在 Javadoc 注释中嵌入已定义的”zone“:

/** 
 * Time Zone 
 * {@snippet file="application.properties" region="zone"} 
 *
 */
public class GreetingsExternalSnippet {
    public void helloBinarySearch() {
        System.out.println("Hi, it's great knowing that binary search uses a loop under the hood");
    }
}

Here, we use the file attribute to define the name of the file.

在这里,我们使用 file 属性来定义文件名。

Here’s the generated documentation:file-attribute-with-snippet-tag

以下是生成的文档:file-attribute-with-snippet-tag

The above image shows the snippet from the properties file.

上图显示了属性文件中的代码段。

3.3. @highlight Tag

3.3.@highlight 标记

Furthermore, we can highlight a section of a code snippet with the @highlight tag to call for attention.

此外,我们还可以使用 @highlight 标记突出显示代码片段的某一部分,以引起注意

Let’s modify the helloBaeldung() method to highlight the section that prints greetings to the console:

让我们修改 helloBaeldung() 方法,以突出显示向控制台打印问候语的部分:

/** 
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung"); // @highlight
 * }
 * }
 */

Here, the @highlight tag highlights the line where we declare it:highlighting-section-of-a-code

在这里,@highlight 标记将高亮显示我们声明它的一行:highlighting-section-of-a-code

Additionally, we can be more specific on the string to highlight:

此外,我们还可以更具体地突出字符串:

/** 
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung"); // @highlight substring="println"
 * } 
 * } 
 */

Here, we highlight “println” by using the substring attribute:highlighting-a-specific-text-in-code-snippet

在此,我们通过使用 substring 属性来突出显示”println“:highlighting-a-specific-text-in-code-snippet 属性:<aref=”/wp-content/uploads/2023/09/highlighting-a-specific-text-in-code-snippet-2.

Furthermore, we can extend the scope of the @highlight tag by using the region attribute and the @end tag:

此外,我们还可以通过使用 region 属性和 @end 标记来扩展 @highlight 标记的范围:

/**
 * highlighting texts on multiple lines
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung"); // @highlight region substring="println"
 *     String country = "USA";
 *     System.out.println("Hello From Team " + country); // @end
 *     
 * }
 * }
 */

The above code uses the region attribute to define the beginning of the scope of the substring to highlight. Finally, we use the @end tag to mark the end of the scope.

上述代码使用 region 属性定义了要高亮显示的子串范围的起始位置。最后,我们使用 @end 标记来标记范围的结束。

The generated documentation highlights the specified substring:highlight-tag-to-mark-multiple-strings

生成的文档会突出显示指定的子串:highlight-tag-to-mark-multiple-strings

Here, the substring “println” is highlighted in the specified scope.

在这里,子字符串”println“在指定的范围内突出显示。

3.4. @replace Tag

3.4.@replace 标记

The @replace tag helps to modify texts within a snippet.

@replace标记有助于修改片段中的文本

Let’s see an example that uses the @replace tag:

让我们来看一个使用 @replace 标记的示例:

/**
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung"); // @replace regex='".*"' replacement="..."
 * }
 * }
 */

Here, we replace the displayed text with three dots:replacing-displayed-text-with-replace-tag

在这里,我们用三个点替换显示的文本:replacing-displayed-text-with-replace-tag <a href=”/wp-content/uploads/2023/09/replacing-displayed-text-with-replace-tag-2.

This can be useful in a case where we want to modify the displayed text.

当我们要修改显示的文本时,这将非常有用。

We can use the @link tag to link to an existing documentation.

我们可以使用 @link 标记来链接到现有文档

First, we define the @link tag in the snippet. Then, we specify the text and the target link:

首先,我们在代码段中定义 @link 标记。然后,我们指定文本和目标链接:

/**
 * Linking Text
 * {@snippet :
 * public void helloBaeldung() {
 *     System.out.println("Hello From Team Baeldung"); // @link substring="System.out" target="System#out"
 * }
 * }
 */

The above code links System.out to an official documentation on how to use it.

上述代码将 System.out 链接到如何使用它的官方文档。

Here’s the generated Javadoc:link-tag-with-in-snippet-to-link-to-other-javadoc

以下是生成的 Javadoc:link-tag-with-in-snippet-to-link-to-other-javadoc <a href=”/wp-content/uploads/2023/09/link-tag-with-in-snippet-to-link-to-other-javadoc-1.

It shows that System.out has a link on it.

它显示System.out上有一个链接。

4. Conclusion

4.结论

In this article, we learned how to use the @snippet tag to add code snippets to a Javadoc comment. Additionally, we saw how to use in-line and external code snippets with other tags and attributes.

在本文中,我们学习了如何使用 @snippet 标记在 Javadoc 注释中添加代码片段。此外,我们还了解了如何将内联和外部代码片段与其他标记和属性一起使用。

The @snippet tag provides easy code integration compared to the @code tag. Syntax highlighting and code validation make @snippet a great Javadoc tool.

@code 标签相比,@snippet 标签可轻松实现代码集成。语法高亮和代码验证功能使 @snippet 成为一款出色的 Javadoc 工具。

As always, the complete source code for the examples is available over on GitHub.

与往常一样,这些示例的完整源代码可在 GitHub 上获取。