JDK 18:Java API文档中的代码片段
OpenJDK 18 Early-Access Build **16(2021/9/23)**现已发布,其中包括针对JDK 18的JEP 413("Java API文档中的代码片段")的实现。JEP 413的目标是 "为JavaDoc的标准Doclet引入一个@snippet 标签,以简化API文档中的源代码示例",JEP本身涵盖了Javadoc的语法和支持的功能。 **{@snippet}**标签所支持的语法和功能。
JEP 413介绍了新的 **{@snippet }**Javadoc标签。
我们引入了一个新的内联标签,
{@snippet ...} ,用于声明将出现在生成的文档中的代码片段。它可以用来声明内联片段(代码片段包含在标签本身)和外部片段(代码片段从一个单独的源文件中读取)。
JEP对Javadoc标签所支持的内容和语法有更详细的说明。 **{@snippet }**支持什么,以及它的语法是什么。这篇文章提供了一个小小的尝试 **{@snippet }**给基于Javadoc的文档带来了什么,本帖中包含的代码列表可在GitHub上找到。
这第一份精心设计的代码清单使用了 **{@snippet }**:
package dustin.examples.jdk18.javadoc;
/**
* Demonstrates {@code @snippet} Javadoc tag targeted for JDK
* as part of JEP 413 (AKA Bug JDK-8201533):
* <ul>
* <li>https://openjdk.java.net/jeps/413</li>
* <li>https://bugs.openjdk.java.net/browse/JDK-8201533</li>
* </ul>
*
* An instance of this class is obtained via my {@link #newInstance()} method
* rather than via a constructor.
*
* {@snippet :
* final SnippetExample instance = SnippetExample.newInstance(); // @highlight substring="newInstance"
* instance.processIt();
* }
*/
public class SnippetExample
{
/**
* No-arguments constructor not intended for public use.
* Use {@link #newInstance()} instead to get an instance of me:
* {@snippet :
* final SnippetExample instance = SnippetExample.newInstance(); // @highlight substring="newInstance"
* }
*/
private SnippetExample()
{
}
/**
* Preferred approach for obtaining an instance of me.
*
* @return Instance of me.
*/
public SnippetExample newInstance()
{
return new SnippetExample();
}
/**
* Performs valuable processing.
*/
public void processIt()
{
}
}
当上述代码在javadoc工具中使用 **-private**选项运行上述代码时,会在HTML中生成类和无参数构造器的代码片段。还请注意,在生成的HTML中,"突出显示 "的部分有粗体强调。
生成的类级文档与片段:
生成的方法级文档与片段:
我认为有一个领域 **{@snippet }**可能特别有用的一个领域是在包文档中。一个用于包描述的代码例子显示在下一个代码列表中,其内容为 **package-info.java**:
/**
* Examples and demonstrations of Javadoc-related capabilities.
*
* The main entrypoint for the snippets example is the {@link SnippetExample} class:
* {@snippet :
* final SnippetExample instance = SnippetExample.newInstance(); // @highlight substring="SnippetExample" @link substring="SnippetExample.newInstance()" target="SnippetExample#newInstance()"
* }
*/
package dustin.examples.jdk18.javadoc;
这个包级文档的生成的HTML输出显示在下一张截图中:
在基于Javadoc的文档中包含代码片段的挑战之一是,用于展示代码的标签(如<pre>,<code>, 和{@code} )会使Javadoc注释在直接查看源码而不是通过生成的HTML时不那么容易阅读。Javadoc标签 **{@snippet }**Javadoc标签可以使代码在生成的HTML中表现得更好,而在源代码本身中却不那么分散注意力。JEP 413解决了目前在Javadoc中包含代码片段的方法的缺点,并总结了如何 **{@snippet }**解决这些缺点。
解决所有这些问题的一个更好的方法是提供一个带有元数据的新标签,允许作者隐式或显式地指定内容的种类,以便它可以被验证并以适当的方式呈现。允许将片段放在单独的文件中也是很有用的,这些文件可以由作者喜欢的编辑器直接操作。
*
JEP 413包含了更多的关于应用的细节。 **{@snippet }**的应用,包括引用外部文件中的代码的能力。


