对象和类比较器

时间:2014-06-16 14:57:59

标签: java class comparison equals

我想比较两个对象:

isEqual(Object left, Object right);

但是,当我通过课程java.lang.Integerclass java.lang.String时,他们都会被视为班级类型,我无法将其与准确性进行比较。还有其他办法吗?

public boolean isEqual(Object left, Object right) {

    Class<?> leftClass = left.getClass(); 
    Class<?> rightClass = right.getClass();

    // if classes are different return false
    if (!leftClass.equals(rightClass)) { //leftClass and rightClass both have the value class java.lang.Class
        if (!(leftClass.isAssignableFrom(rightClass) || rightClass.isAssignableFrom(leftClass))) {
            return false;
        }
    }
return true
}

2 个答案:

答案 0 :(得分:1)

如果leftright可以是对象和类,那么您必须首先检查:

Class<?> leftClass;
if( left instanceof Class) {
  leftClass = (Class)left;
}
else {
  leftClass = left.getClass();
}

//or in one line:
Class<?> leftClass = left instanceof Class ? (Class)left : left.getClass();

//do the same for right 

如果leftright只能 成为类,那么我会将参数类型更改为Class<?> left等。

答案 1 :(得分:0)

如果你想测试一个String和一个Integer是否相等,这对我来说意味着你要测试String的相等性。所以,我会这样做 -

public boolean isEqual(Object left, Object right) {
  if (left == null) return right == null;
  else if (right == null) return false;
  return left.toString().equals(right.toString());
}