找到你要的答案

Q:How to make java interface / abstract class that uses per-field equals instead of default equals?

Q:如何使java接口/抽象类,使用每个字段等于代替默认等于?

I have a process which requires creating java classes which will serve as keys in a table (as a key in a Spark framework). To get the correct functionality, I need to override the default object equals() and hash code methods with functions that perform field-wise comparison. (I generate this automatically in Eclipse/Intellij).

The problem is that each time I create a new class or make a change to the existing class - I need to re-generate the equals/hash. This is a buggy process, since if I forget to regenerate the equals there is no compile error.

Is there any way in Java to create classes which have as default a field-wise equals/hash code?

我有一个过程,需要创建java类,将作为表中的键(如火花框架的一个关键)。得到正确的功能,我需要重写,进行现场比对功能默认对象equals()和哈希代码的方法。(我生成这个自动在Eclipse / IntelliJ)。

问题是,每当我创建一个新类或对现有类进行更改时,我需要重新生成相等/散列。这是一个错误的过程,因为如果我忘记再生等于没有编译错误。

有没有任何方法来创建java作为默认字段智慧等于/哈希代码的课程吗?

answer1: 回答1:

Such feature is provided by Lombok project. It includes annotation processor which is executed during compilation. It's compatible with Eclipse, maven, ant and so on. You should just annotate your class with @EqualsAndHashCode and it will automatically create the equals and hashCode for you.

这些特征是由龙目岛项目提供。它包括在编译过程中执行的注释处理器。它是用Eclipse,Maven兼容、蚂蚁等。你应该添加@ equalsandhashcode班级,它会自动为您创建equals和hashCode。

answer2: 回答2:

You could implement such a check in a "generic" way ... using reflection. Meaning: use reflection to automatically fetch all fields of objects; and compare each of them.

But of course, using reflection like that is probably a great way to kill your performance.

Thus a more "serious" answer is: consider how exactly your "process which requires creating java classes" works. Maybe you can replace the "manual creation of new Java classes" with an automated step. Meaning: do not write Java classes yourself. Instead; built a generator that creates these classes for you (including equals and hashCode).

Or, third and again less serious option: use Scala for these classes. When creating "case classes"; the Scala compiler takes care of equals, hashCode, ... you name it.

您可以以“通用”的方式实现这样的检查…使用反射。使用反射自动获取对象的所有字段,并对它们进行比较。

但当然,使用反射,这可能是一个伟大的方式来杀死你的表现。

因此,一个更“严重”的回答是:考虑你到底”的过程,需要创建java类”的作品。也许你可以代替人工创造新的java类“自动步。意义:不写自己的java类。相反;建了一个生成器创建这些类你(包括equals和hashCode)。

或者,第三又不太严重的选项:使用Scala这些类。当创建“类”;Scala编译器负责等于hashCode,…你说出来。

java  design  hash  equals