java比较对象:使用反射?
我有一个对象,它本身有多个对象作为字段。我的问题是,我有两个此类对象,我想比较这两个对象。我知道我可以执行等于、比较等操作,但是有没有办法使用反射来获取对象的属性并进行比较。
例如,如果我有一个汽车对象,它是车轮对象,它有轮胎对象,它有螺栓对象。请记住,上述所有对象都是单独的,而不是嵌套类。如何比较 2 个汽车对象?
有什么帮助值得赞赏吗?
谢谢
I have an object which itself has multiple objects as fields. The question I have is, I have two objects of these kind and I want to compare these two. I know I can do equals, comparator etc. but is there a way to use reflection to get the properties of the object and make comparison.
for example, if I have a Car object, which as wheels object, which has tires object, which has bolts object. Please remember all the above objects are individual and not nested classes. How do I compare 2 car objects?
Any help is appreciated?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Apache Commons Lang 有一个 EqualsBuilder 类正是这样做的(请参阅
reflectionEquals()
方法)EqualsBuilder
还为特定字段的空安全比较提供了更明确的方法,这使得编写“正确”(即非反射)等于方法稍微不那么繁琐。Apache Commons Lang has an EqualsBuilder class that does exactly this (see the
reflectionEquals()
methods)EqualsBuilder
also provides more explicit methods for null-safe comparison of specific fields, which makes writing "proper" (i.e. non-reflective) equals methods a bit less onerous.是正确的做法。不建议通过反射进行自动比较。一方面,“状态”是一个比反射属性比较更通用的概念。
你可以写一些进行深度反射比较的东西,但它有点没有抓住重点。
is the correct approach. Automatic comparison via reflection is not recommended. For one thing "state" is a more generic concept than reflected property comparison.
You could write something that did deep reflection comparison but it's kinda missing the point.
大多数现代 IDE 都有 hashcode 和 equals 生成器,让您可以选择要考虑的属性。这些人的表现轻而易举地击败了反思型同行。
Most modern IDE's have generators for hashcode and equals which let you select the properties to take into account. Those beat performance of their reflective counterparts easily.
这个想法很有趣,但请注意反射可能会很慢。如果您需要进行大量比较,或者您将对象放入进行比较的集合类中(例如
HashMap
、HashSet
等),则通过反射比较对象可能成为性能瓶颈。The idea is interesting, but please be aware that reflection can be slow. If you need to do a lot of comparisons, or you are putting your objects in collection classes that do comparisons (for example
HashMap
,HashSet
etc.) then comparing objects via reflection can become a performance bottleneck.