Java 14:记录
Java 14是在幾周前問世的,它引入了Record類型,它是一個不變的數據載體類,旨在容納一組固定的字段。 請注意,這是預覽語言功能 ,這意味著必須使用--enable-preview標志在Java編譯器和運行時中顯式啟用它。
我將直接介紹一個Book記錄示例,該記錄旨在保存書名,作者,出版日期和價格。 這是記錄類的聲明方式:
public record Book(String title, String author, LocalDate publishDate, double price) { }您可以使用javap查看編譯器自動生成的代碼:
public final class Book extends java.lang.Record { public Book(java.lang.String, java.lang.String, java.time.LocalDate, double ); public java.lang.String title(); public java.lang.String author(); public java.time.LocalDate publishDate(); public double price(); public java.lang.String toString(); public final int hashCode(); public final boolean equals(java.lang.Object); }如上所示,編譯器自動生成了構造函數,getter方法, hashCode , equals和toString ,從而使我們不必鍵入很多樣板代碼。
但是,記錄不僅可以節省鍵入時間。 它們還使您的意圖明確了,您希望將不可變數據項建模為一組相關字段。
用于現場驗證的緊湊型構造器
現在,假設您要向記錄添加驗證和默認值。 例如,您可能要驗證未以負價或未來發布日期創建Book記錄。 可以使用緊湊的構造函數來完成此操作,如下所示:
public record Book(String title, String author, LocalDate publishDate, double price) { //compact constructor (no parameter list), used for validation and setting defaults public Book { if (price < 0.0 ) { throw new IllegalArgumentException( "price must be positive" ); } if (publishDate != null && publishDate.isAfter(LocalDate.now())) { throw new IllegalArgumentException( "publishDate cannot be in the future" ); } this .author = author == null ? "Unknown" : author; } }緊湊的構造函數沒有參數列表。 它驗證價格和發布日期,并為作者設置默認值。 在此構造函數中未分配的字段(即title , publishDate和price )在此構造函數的末尾隱式初始化。
替代構造函數和其他方法
記錄使您可以定義其他方法,構造函數和靜態字段,如下面的代碼所示。 但是,請記住,從語義上說,一條記錄被設計為數據載體,因此,如果您覺得要添加額外的方法,則可能是需要一個類而不是一條記錄。
public record Book(String title, String author, LocalDate publishDate, double price) { // static field private static final String UNKNOWN_AUTHOR = "UNKNOWN" ; // compact constructor, used for validation and setting defaults public Book { if (price < 0 ) { throw new IllegalArgumentException( "price must be positive" ); } if (publishDate != null && publishDate.isAfter(LocalDate.now())) { throw new IllegalArgumentException( "publishDate cannot be in the future" ); } this .author = author == null ? UNKNOWN_AUTHOR : author; ? UNKNOWN_AUTHOR : author; } // static factory constructor public static Book freeBook(String title, String author, LocalDate publishDate) { return new Book(title, author, publishDate, 0.0 ); } // alternative constructor, without an author public Book(String title, LocalDate publishDate, double price) { this (title, null , publishDate, price); } // additional method to get the year of publish public int publishYear() { return publishDate.getYear(); } // override toString to make it more user friendly @Override public String toString() { return String.format( "%s (%tY) by %s for £%.2f" , title, publishDate, author, price); } }翻譯自: https://www.javacodegeeks.com/2020/04/java-14-records.html
總結
以上是生活随笔為你收集整理的Java 14:记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hazelcast_Hazelcast的
- 下一篇: 无线网卡驱动linux版本(无线网卡驱动