我有一個同學,在一家小型互聯網公司做Java后端開發,最近他們公司新來了一個技術總監,這位技術總監對技術細節很看重,一來公司之后就推出了很多"政策",比如定義了很多開發規范、日志規范、甚至是要求大家統一使用Idea進行開發。
其中有一項,就是禁止使用Lombok,但是他并沒有明確的說明原因,我的同學是一個“懶加載的CRUD程序員”,不用Lombok,豈不是要費很多事兒?
他特意百度了一下,是這樣說的。
看似很有道理,條條是道,但我認為有些以偏概全,自以為是了。
目前國內大多數Java項目,采用的都是JDK1.8,因為它夠穩定,功能也完全夠用,但是,如果哪一天,你的客戶心血來潮,就是想用JDK11,甚至JDK17,此時,你會發現Lombok不好用了,于是,不得不將好幾百個實體類,通過idea生成get/set、equals、toString等方法,很煩躁。
當你的客戶獲取到你的源代碼之后,他也想看看,運行一下,此時發現沒安裝Lombok,報錯了,安裝Lombok,不了解這是什么,還要去百度學習一下,被迫營業,很煩躁。
這是一種弊大于利、得不償失的操作。
我在開發過程中,遇到這樣一個問題,就是Lombok造成的。
@Datapublic class Animals { private Integer id; private String name;}
@Datapublic class Dog extends Animals{ private String cry;}
我去,哪吒,你在侮辱我嗎?一個小狗和一個老狗怎么可能會相等?這什么JB玩意,我去打游戲了,你自己玩吧~
很多小伙伴,看到這,直接蒙了,根本不知道為什么?
這個時候,可以看看編譯后的class。
public boolean equals(final Object o) { if (o == this) { return true; } else if (!(o instanceof Dog)) { return false; } else { Dog other = (Dog)o; if (!other.canEqual(this)) { return false; } else { Object this$cry = this.getCry(); Object other$cry = other.getCry(); if (this$cry == null) { if (other$cry != null) { return false; } } else if (!this$cry.equals(other$cry)) { return false; } return true; } }}
為什么equals只比較一個屬性cry,而Animals比較了兩個屬性?
public boolean equals(final Object o) { if (o == this) { return true; } else if (!(o instanceof Animals)) { return false; } else { Animals other = (Animals)o; if (!other.canEqual(this)) { return false; } else { Object this$id = this.getId(); Object other$id = other.getId(); if (this$id == null) { if (other$id != null) { return false; } } else if (!this$id.equals(other$id)) { return false; } Object this$name = this.getName(); Object other$name = other.getName(); if (this$name == null) { if (other$name != null) { return false; } } else if (!this$name.equals(other$name)) { return false; } return true; } }}
根據子類自身的字段值和從父類繼承的字段值 來生成hashcode,當兩個子類對象比較時,只有子類對象的本身的字段值和繼承父類的字段值都相同,equals方法的返回值是true。
根據子類自身的字段值 來生成hashcode, 當兩個子類對象比較時,只有子類對象的本身的字段值相同,父類字段值可以不同,equals方法的返回值是true。
@Data@EqualsAndHashCode(callSuper = true)public class Dog extends Animals{ private String cry;}
本文鏈接:http://www.tebozhan.com/showinfo-26-16529-0.html在Lombok的加持下,“小狗”.Equals(“老狗”) = True
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com