Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Java compare two objects and get unequal fields

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "Java how to compare two objects and get unequal fields". In daily operation, I believe many people have doubts about how Java compares two objects and get unequal fields. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how Java compares two objects and gets unequal fields". Next, please follow the editor to study!

Write at the front

In our work, we often encounter the need to compare whether two objects are equal, and if not, to take out unequal fields.

The following scenarios require us to compare an object:

Data comparison

Do a unit test to assert whether the object is equal

The front end requires that unequal fields be highlighted

This kind of requirement is actually very simple, but how to solve this kind of demand gracefully?

The common practice is to override the object's equals method. However, rewriting the equals method has many disadvantages, such as:

Every time the property of an object changes, be sure to rewrite it (rest assured, you will forget it)

There can be only one equals method per object, but you may need different comparison rules

You can only compare whether two objects are equal, and it is impossible to know which attributes are different.

The automatically generated equals method cannot be compared based on the getter method

The object comes from a third-party dependency and cannot override the equals method

Therefore, the implementation of a general-purpose comparator can reduce a lot of unnecessary trouble and help us to meet this kind of requirements well.

Origin

I have this requirement when I do data synchronization. I want to import the data from the database into ES through certain rules. After the import is completed, how to compare whether the data on both sides are consistent? At this time, a good comparator is my very good helper.

In addition, when I do unit tests, I find that this comparator is also very helpful when I often need to make assertEquals assertions of the return value of the method under test and the expected result. I find that many colleagues often encounter similar needs.

So I found time to realize it by myself.

Realize

Using reflection to compare incoming objects, a field-based comparator and a Getter method-based comparator are provided, and with full consideration of extensibility, users can rewrite the field alignment rules. The function is relatively simple, the code implementation is not difficult, and made a lot of comments, the specific implementation can directly view the source code.

UML figure:

Usage

Because it has been uploaded to the maven repository, it is very convenient for us to use:

Add maven dependency

Com.github.dadiyang equator 1.0.3

Initialize and call the method

Equator equator = new GetterBaseEquator (); User user1 = new User (...); User user2 = new User (...); / / determine whether attributes are completely equal equator.isEquals (user1, user2); / / get different attributes List diff = equator.getDiffFields (user1, user2); extend

We can customize the alignment rules by inheriting and overriding the isFieldEquals method. For example, when we do a unit test, the database usually does not save milliseconds for the comparison of fields of type Date, while the Date object we new out contains the number of milliseconds, so we need to ignore the number of milliseconds of the date when comparing objects containing fields of type Date. You can then customize it by overriding the isFieldEquals method:

/ * * date does not save milliseconds in the database, so special processing is required. When comparing times, ignore milliseconds * * @ author dadiyang * @ date 2019-3-23 * / public class MmInsensitiveEquator extends GetterBaseEquator {@ Override protected boolean isFieldEquals (FieldInfo fieldInfo) {if (fieldInfo.getFirstVal () instanceof Date) {Date first = (Date) fieldInfo.getFirstVal (); Date second = (Date) fieldInfo.getSecondVal () If (Objects.equals (first, second)) {return true;} / / ignore milliseconds return Objects.equals (Math.round (first.getTime () / 1000), Math.round (second.getTime () / 1000));} return super.isFieldEquals (fieldInfo) }} at this point, the study on "how Java compares two objects and gets unequal fields" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report