Ser*_*gey 6 java java-14 java-record java-16
当我们在 Java 中使用类时,为每个类字段/方法添加 JavaDoc/注释非常简单:
class Product {
//Product unique identifier
private int id;
}
Run Code Online (Sandbox Code Playgroud)
如果我们将这些类迁移到 Java 记录,则不清楚在这种情况下编写注释/JavaDocs 的最佳实践是什么:
record Product(int id, String name, double price) {
}
Run Code Online (Sandbox Code Playgroud)
因为现在所有字段都在一行中声明。
好吧,关于文档,您有两种选择,要么在记录级别使用 Javadoc,要么使用块注释,我在下文中都使用了
/**
* My record example
*
* @param string does stringy things
* @param integer does integery things
*/
public record Example(
/*
Does stringy things
*/
String string,
/*
Does integery things
*/
int integer
){};
Run Code Online (Sandbox Code Playgroud)
这是来自 JDK 本身的 Javadoc 示例
/**
* A serializable cartesian point.
*
* <em>This example illustrates the documentation of a serializable record.</em>
*
* @param x the x coordinate
* @param y the y coordinate
*/
public record SerializablePoint(int x, int y) implements Serializable { }
Run Code Online (Sandbox Code Playgroud)
这是一个带有注释块的示例(即使它没有任何参数)
public record NoWarningRecord(/* no components */) {
// No explicit constructor; use canonical one.
}
Run Code Online (Sandbox Code Playgroud)
id第二个片段中的、name、 和price不是字段,它们是记录组件。Yassin的回答已经提到了如何实现它,但为了完整起见,以下是如何实现的:
/**
* A very complex Product description.
*
* @param id Product identifier; appears in "Record Components".
* @param name Product name appears; in "Record Components".
* @param price Product price; appears in "Record Components".
*/
public record Product(int id, String name, double price){}
Run Code Online (Sandbox Code Playgroud)
标准 doclet 将忽略以下内容:
public record Product(
/**
* This comment would be ignored.
*/
int id,
/*
* Ignored
*/
String name,
// Ignored
double price) {}
Run Code Online (Sandbox Code Playgroud)
如果您有一个字段,那么您可以向其中添加 Javadoc:
public record Product(...) {
/**
* Max Product price, appears in "Field Summary".
* <p>
* Appears in "Field Details".
*/
public static final double MAX_PRICE = Integer.MAX_VALUE >> 2;
}
Run Code Online (Sandbox Code Playgroud)
要将 Javadoc 添加到规范构造函数中,可以使用紧凑风格:
public record Product(...) {
/**
* Product's compact canonical constructor, appears in "Constructor Summary".
* <p>
* In "Constructor Details".
*
* @param id Product identifier, appears in "Constructor Details"
* not in "Record Components".
* @param name Product name, appears in "Constructor Details"
* not in "Record Components".
* @param price Product price, appears in "Constructor Details"
* not in "Record Components".
* @throws IllegalArgumentException Allowed price range
* ({@code 0.0D}, {@link Product#MAX_PRICE}]
*/
public Product {
if (price <= 0 || price > MAX_PRICE) throw new IllegalArgumentException();
}
}
Run Code Online (Sandbox Code Playgroud)