Java equals(): reflect or not

This problem is related to the equals () method of objects that cover a large number of fields First of all, let me say that this large object cannot be decomposed into multiple components without violating the OO principle, so telling me "no class should have more than x fields" won't help

Go on, when I forget to examine an equal field, the problem is over Therefore, my equals method is incorrect Then I think with reflection:

--code removed because it was too distracting--

The purpose of this post is not necessarily to refactor the code (this is not even the code I use), but to get input on whether this is a good idea

advantage:

>If a new field is added, it is automatically included > this method is more concise than the 30 statement

Disadvantages:

>If a new field is added, it will be automatically included. Sometimes this is undesirable > performance: this must be slower. I don't think it's necessary to break the analyzer > it's a little ugly to ignore a specific field in the comparison

Any ideas?

Solution

If you do need to whitelist it for performance reasons, consider using comments to indicate the fields to compare In addition, if your field does not have a good implementation of equals (), this implementation will not work properly

PS: if you go to a route equal to (), don't forget to do something like hashcode ()

P. P.S. I believe you have considered hashcodebuilder and equalsbuilder

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>