博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lombok---@EqualsAndHashCode(callSuper = true)的使用
阅读量:4181 次
发布时间:2019-05-26

本文共 3036 字,大约阅读时间需要 10 分钟。

package com.xiaobu.entity;import lombok.Data;import java.io.Serializable;/** * @author xiaobu * @version JDK1.8.0_171 * @date on  2020/9/1 9:24 * @description */@Datapublic class Father implements Serializable {
private static final long serialVersionUID = -3605840195099107460L; private int age; private String name;}
package com.xiaobu.entity;import lombok.Data;import java.io.Serializable;/** * @author xiaobu * @version JDK1.8.0_171 * @date on  2020/9/1 9:24 * @description */@Datapublic class Son  extends Father implements Serializable {
private static final long serialVersionUID = -3605840195099107460L; private String address; public static void main(String[] args) {
Son son1 = new Son(); son1.setAge(1); son1.setName("laowang"); son1.setAddress("shenzhen"); Son son2 = new Son(); son2.setAge(2); son2.setName("laoliu"); son2.setAddress("shenzhen"); System.out.println("son2 .equals(son1) " + son2 .equals(son1) ); }}

结果为true。

1599011252(1).png

在Son类添加 @EqualsAndHashCode(callSuper = true) 默认为false。

可以看出没有@EqualsAndHashCode(callSuper = true)的Son类编译后的equals()方法

public boolean equals(final Object o) {
if (o == this) {
return true; } else if (!(o instanceof Son)) {
return false; } else {
Son other = (Son)o; if (!other.canEqual(this)) {
return false; } else {
Object this$address = this.getAddress(); Object other$address = other.getAddress(); if (this$address == null) {
if (other$address != null) {
return false; } } else if (!this$address.equals(other$address)) {
return false; } return true; } } }

有@EqualsAndHashCode(callSuper = true)的Son类编译后的equals()方法

public boolean equals(final Object o) {
if (o == this) {
return true; } else if (!(o instanceof Son)) {
return false; } else {
Son other = (Son)o; if (!other.canEqual(this)) {
return false; } else if (!super.equals(o)) {
return false; } else {
Object this$address = this.getAddress(); Object other$address = other.getAddress(); if (this$address == null) {
if (other$address != null) {
return false; } } else if (!this$address.equals(other$address)) {
return false; } return true; } } }

可以看出来后者多了个

else if (!super.equals(o)) {
return false; }

拓展:

Data 注解生成的 toString 方法也只包含了子类自有属性。

解决方案一样,加上 @ToString(callSuper = true) 注解,其实这里真正重要的是注解中的属性,callSuper = true,加上注解后打印结果如下:

参考:

转载地址:http://izgai.baihongyu.com/

你可能感兴趣的文章
可怕啊,阿里面试!
查看>>
疯传!某大厂P8面试题库遭到泄露!
查看>>
中国编程第一人,一人抵一城!
查看>>
【微信红包封面】最新!最全!
查看>>
最近线上发生的两个坑爹锅!
查看>>
腾讯QQ的回应来了~
查看>>
最新5款微信红包封面,来了 !!!
查看>>
哦嚯,被微服务给坑了...
查看>>
SCI审稿人亲授:机器学习在智能化时代下的应用
查看>>
安卓微信 8.0 内测版来啦!
查看>>
我劝你不要再留QQ邮箱了
查看>>
真香!用 4K 高清显示器写代码!(包邮送一台)
查看>>
神器!各行业必备!低调使用
查看>>
B 站,牛逼!
查看>>
微信状态视频、图片素材来啦!
查看>>
再见了!锤子!!!
查看>>
LeetCode 全站第一,牛逼!
查看>>
为什么全网都在劝你学Java、Python,而不是C++?
查看>>
卧槽!阿里巴巴《算法笔记》开源了,完整版PDF开放下载!
查看>>
百度的骚操作。。。
查看>>