EqualsBuilder与自己的equals方法 [英] EqualsBuilder vs own equals method
问题描述
我刚刚在等于
方法中使用 EqualsBuilder()
遇到了代码。使用它而不是编写(或从eclipse生成)我们自己的逻辑是否有任何优势?一个简单的例子会更有帮助。
I just came across a code using EqualsBuilder()
in equals
method. Is there any advantage of using it instead of writing (or generating from eclipse) our own logic? A simple example would be more helful.
编辑:如果没有任何好处而不是在课程中使用更少的代码,是不是有反射的开销?
Edit : If it doesn't have any benefits than having less code in the class, isn't there is overhead of reflection?
推荐答案
有几种方法可以解决这个问题。
There are a few ways to approach this.
-
你可以自己动手 - 最有可能让
出现微妙的错误。
You can roll your own - that has the highest likelihood of getting something subtle wrong.
您可以让Eclipse为您生成equals和hashCode方法 - 这会留下大量代码,会受到无意的编辑,并且在课程中无法更新获得一个新领域。
You can have Eclipse generate your equals and hashCode methods for you - that leaves a lot of code in place, subject to inadvertent edits, and subject to failure to update when the class acquires a new field.
你可以使用EqualsBuilder;它避免了上述问题。
You can use EqualsBuilder; it avoids the aforementioned problems.
最重要的是,至少根据我的经验,你可以使用lombok的 EqualsAndHashCode 注释。
Best of all, at least in my experience, you can use lombok's EqualsAndHashCode annotation.
这篇关于EqualsBuilder与自己的equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!