简体   繁体   中英

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. The user is required to override the equals function and provide us with it. 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?

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.)

There is no way to do such a thing with the reflection API that I know of.

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 . The class designer should be providing you with the proper hashCode using the fields that they decided to use.

Perhaps your scheme could use that hashCode returned value as a start.

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.

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