Java 生成equals和hashcode时忽略属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19506166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ignore property when generating equals and hashcode
提问by Jason McD
Let's say I have a class Customer:
假设我有一个类客户:
public class Customer {
private String firstName;
private String lastName;
private String doNotAddMeToEquals;
//Getters and Setters below
}
I'm using the Guava Eclipse Pluginin Eclipse to generate my equals() and hashCode() methods; however, I could just as well use the eclipse -> Source -> Generate HashCode / Equals. Either way...doesn't matter.
我在 Eclipse 中使用Guava Eclipse 插件来生成我的 equals() 和 hashCode() 方法;但是,我也可以使用 eclipse -> Source -> Generate HashCode / Equals。不管怎样……都无所谓。
Is there a way to Annotate property doNotAddMeToEquals such that when I generate the equals & hashcode methods with the guava plugin that property doesn't show in the list?
有没有办法对属性 doNotAddMeToEquals 进行注释,这样当我使用番石榴插件生成 equals 和 hashcode 方法时,该属性不会显示在列表中?
Without altering the plugin or creating a template.
无需更改插件或创建模板。
Thanks in Advance!!
提前致谢!!
采纳答案by aet
It sounds like what you want is something like this:
听起来你想要的是这样的:
http://projectlombok.org/features/EqualsAndHashCode.html
http://projectlombok.org/features/EqualsAndHashCode.html
It lets you use annotations to drive what properties are included in the equals and hashcode methods.
它允许您使用注释来驱动 equals 和 hashcode 方法中包含哪些属性。
回答by i-tms
Using Lombok you can exclude properties from hashcode and equals like such as:
使用 Lombok,您可以从 hashcode 和 equals 中排除属性,例如:
@EqualsAndHashCode(exclude = {"nameOfField"})
That would be in your case
那就是你的情况
@EqualsAndHashCode(exclude = {"doNotAddMeToEqualsAndHashCode"})