问题描述
当我们在 Java 中使用类时,为每个类字段/方法添加 JavaDoc/注释非常简单:
class Product {
//Product unique identifier
private int id;
}
如果我们将这些类迁移到 Java 记录,那么在这种情况下编写注释/JavaDocs 的最佳实践是什么尚不清楚:
record Product(int id,String name,double price) {
}
因为现在所有字段都在一行中声明。
解决方法
嗯,关于文档,你有两种选择,要么使用记录级别的 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
){};
这是来自 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 { }
这是一个带有注释块的示例(即使它没有任何参数)
public record NoWarningRecord(/* no components */) {
// No explicit constructor; use canonical one.
}
,
第二个代码段中的 id
、name
和 price
不是字段,它们是记录组件。 Yasin 的回答已经提到了如何实现它,但只是为了完整起见,您可以这样做:
/**
* 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){}
标准 doclet 将忽略以下内容:
public record Product(
/**
* This comment would be ignored.
*/
int id,/*
* Ignored
*/
String name,// Ignored
double price) {}
如果您有一个字段,那么您可以向其中添加 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;
}
要将 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();
}
}