简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM