8

当我们在 Java 中使用类时,为每个类字段/方法添加 JavaDoc/comment 非常简单:

class Product {
    //Product unique identifier
    private int id;
}

如果我们将这些类迁移到 Java 记录,那么在这种情况下编写注释/JavaDocs 的最佳实践是不清楚的:

record Product(int id, String name, double price) {
}

因为现在所有字段都在一行中声明。

4

2 回答 2

11

好吧,关于文档,您有两种选择,要么使用记录级别的 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.
}
于 2021-05-03T20:09:13.383 回答
3

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();
  }
}
于 2021-05-05T13:05:47.163 回答