java比较对象:使用反射? [英] java compare objects: using reflection?
问题描述
我有一个对象本身有多个对象作为字段。我的问题是,我有两个这样的对象,我想比较这两个。我知道我可以做等于,比较器等,但有一种方法使用反射获得对象的属性,并进行比较。
例如,如果我有一个Car对象,它作为轮对象,它有轮胎对象,它有螺栓对象。请记住所有上述对象是单独的,而不是嵌套的类。如何比较2辆汽车物体?
感谢任何帮助?
感谢
public class Car {
private Wheels wheels;
//其他属性
public boolean equals(Object ob){
if(!
Car other =(Car)ob;
//比较属性
if(!wheels.equals(other.wheels))return false;
return true;
}
}
是正确的方法。不推荐通过反射进行自动比较。对于一个事物,状态是一个比反映属性比较更通用的概念。
你可以写一个深层反射比较的东西, >
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
public class Car {
private Wheels wheels;
// other properties
public boolean equals(Object ob) {
if (!(ob instanceof Car)) return false;
Car other = (Car)ob;
// compare properties
if (!wheels.equals(other.wheels)) return false;
return true;
}
}
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.
这篇关于java比较对象:使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!