简体   繁体   English

获取在equals函数内使用的所有实例字段的名称

[英]Getting the names of all the instance fields used inside the equals function

I am working on a project related to hash functions in Java. 我正在从事与Java中的哈希函数相关的项目。 The user is required to override the equals function and provide us with it. 要求用户重写 equals函数并将其提供给我们。 While overriding equals he may use a subset of all the instance fields of the class which I am considering as the important fields of the object. 覆盖等于时,他可以使用该类的所有实例字段的子集,我将其视为对象的重要字段。 How can I extract the names of all the fields that the user uses inside the equals method? 如何提取用户在equals方法内使用的所有字段的名称?

I am able to get the names of all the fields using the Reflection API but I only want those fields that have been used inside the equals method to compare the objects.(Using reflection is not a constraint, I just want a way to solve the problem.) 我可以使用Reflection API来获取所有字段的名称,但我只想在equals方法中使用的那些字段来比较对象。(使用反射不是一种约束,我只想一种解决方法问题。)

There is no way to do such a thing with the reflection API that I know of. 我所知道的反射API无法做到这一点。

The only way that I'm aware of is to read the code. 我知道的唯一方法是阅读代码。

If your project depends on this as a requirement, I fear that you'll have to reconsider it. 如果您的项目依赖于此,我担心您将不得不重新考虑它。

The correct thing to do is to override equals and hashCode together, as defined by Joshua Bloch in Effective Java chapter 3 . 正确的做法是一起重写equalshashCode ,这由Joshua Bloch在Effective Java第3章中定义。 The class designer should be providing you with the proper hashCode using the fields that they decided to use. 类设计器应该使用他们决定使用的字段为您提供适当的hashCode

Perhaps your scheme could use that hashCode returned value as a start. 也许您的方案可以使用该hashCode返回的值作为开始。

The problem is that you have no control over what the developers of libraries you depend on will do. 问题在于,您无法控制所依赖的库开发人员的工作。

If you do have that kind of control, because you only care about classes that you write, then it's another discussion. 如果你有那种控制的,因为你只在乎写的类,那么它的另一个讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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