Java记录和字段注释

当我们在 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.
}


以上是Java记录和字段注释的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>