比较两个通用复杂对象java [英] compare two generic complex objects java
问题描述
我的要求是比较相同未知/通用类型的两个对象。
对象是复杂的。它们可以包含可以包含列表的列表。
My requirement is to compare two objects of the same unknown/generic type. The objects are complex. They can contain Lists which can themselves contain Lists.
因此,我最初的想法是使用Comparator来比较对象,反射
用于发现bean和一些递归处理任何嵌套的
列表对象可能包含。
So, my initial thoughts are to use a Comparator for comparing objects, reflection for discovering all properties of the bean and some recursion to handle any nested lists the objects may contain.
或者,有一个实用程序将为我做所有的,在java ?
or, is there a utility that will do all of that for me, in java?
推荐答案
我目前正在开发一个类似的问题。我可以确认使用java反射,你可以比较相同的未知/通用类型的两个对象。我找到了所需的一切,在这里。下面是关于如何执行的一些细节:
I'm currently working on a similar problem. I can confirm that using java reflection you can compare two objects of the same unknown/generic type. I found everything I needed to do so here. Here is a little rundown on how to do it:
- 在函数中获取两个对象
- 确定ob1的所有字段
- 假设对象的类型相同,您可以使用one字段从两个对象中获取值,然后进行比较,如
field.get(ob1).equals(field.get(ob2)
- Get two objects in a function
- Determine all on ob1's fields
- Assuming the objects are of equal type you can use the the one field to get the value out of both objects and compare, like so
field.get(ob1).equals(field.get(ob2)
比较对象内部的对象是非常困难的,我没有找到一个解决方案,这里是问题:使用反射比较你需要两个对象的项目我还没有发现一种方法从一个对象如果你找不到任何东西,请告诉我。
However, comparing objects inside of objects is far more difficult. I have no found a solution to it and here is the problem: to compare to items using reflection you need two objects. I have not yet discovered a way to extract an object out of an object of unknown type. Let me know if you find anything.
这篇关于比较两个通用复杂对象java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!