英文:
How to Lombok with equals hashcode and toString with two objects that have a cycle?
问题
我有两个类
@Data
class Org {
int id;
Account orgAccount;
...
}
@Data
class Account {
Org org;
}
我有以下对象
var org = new Org();
org.setId(123);
var account = new Account();
org.setOrgAccount(account);
account.setOrg(org);
如果我执行 account.hashCode()
或 account.toString()
,由于循环引用,会导致堆栈溢出。为了解决这个问题,我做了以下操作
@Data
class Account {
@EqualsAndHashCode.Exclude
@ToString.Exclude
Org org;
}
但实际上,我仍然希望对 org 进行比较,但只比较 id
而不是整个对象。在不实现自己的 equals/hashcode 的情况下,有什么最好的方法可以实现这一点?
英文:
I have two classes
@Data
class Org {
int id;
Account orgAccount;
...
}
@Data
class Account {
Org org;
}
And I have a the following objects
var org = new Org();
org.setId(123);
var account = new Account();
org.setOrgAccount(account);
account.setOrg(org);
If I do a account.hashCode()
or account.toString()
I would get a stack overflow because of the cycle. To get around this I do
@Data
class Account {
@EqualsHashCode.Exclude
@ToString.Exclude
Org org;
}
But I actually still want org to be compared, but only for the id
rather than the whole object. What's the best way to do this without implementing your own equals/hashcode?
答案1
得分: 1
我的解决方案是包括一个可以设为`private`的方法,该方法将获取我想要进行比较的值,并将其包括在ToString和EqualsHashCode中。
@Data
class Account {
@EqualsHashCode.Exclude
@ToString.Exclude
Org org;
@EqualsHashCode.Include
@ToString.Include
private int getOrgId() { return org.getId(); }
}
英文:
My solution is to include a method that can be private
that will get the value I want to be compared and include it for ToString and EqualsHashCode
@Data
class Account {
@EqualsHashCode.Exclude
@ToString.Exclude
Org org;
@EqualsHashCode.Include
@ToString.Include
private int getOrgId() { return org.getId(); }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论