How to Lombok with equals hashcode and toString with two objects that have a cycle?

huangapple go评论88阅读模式
英文:

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(); }
}

huangapple
  • 本文由 发表于 2020年4月8日 12:11:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61093204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定