检查一个对象是否与这个对象属于同一个类?

3
我有一个Java中的多个数据对象类型的基类。我想在基类中创建一个equals方法,该方法可以直接用于继承。
相等性由两个对象决定。
  1. belonging to subclasses of the base class. This is easily achievable using

    if (!(anObject instanceof BaseClass))
        return false;
    
  2. having the same ID. The ID field is defined by the base class so we can here test that.

    if (this.id != ((BaseClass) anObject).id)
        return false;
    
  3. belonging to the same class. This is where I have the problem. Two objects may be of different types (and so be in different lists), but have the same ID. I have to be able to distinguish them. How can I do this?


2
你可以使用 Object.getClass().equals(this.getClass()) 来实现这个目的(假设你指的是特定实体的类类型而不是类属性)。 - Luiggi Mendoza
你的意思是 this.getClass() 吗? - Jeroen Vannevel
1
《Effective Java》非常明确地指出:试图扩展值对象并维护“equals”契约几乎是无望的。 - Louis Wasserman
5个回答

9

使用

this.getClass() == anotherObject.getClass()

使用“instanceof”关键字来代替。只有当两个对象属于同一类时,才会返回true(通过引用检查类对象是否相等是安全的)。之后,您可以比较id。


1

如果在实现equals方法时遇到问题,建议阅读本文

简言之:使用this.getClass()==other.getClass()而不是instanceof,因为否则equals()关系将不具有传递性(superInstance.equals(subInstance)为true,但subInstance.equals(superInstance)为false)。


这是正确的;在我的情况下,基类是抽象的,因此不能有它的实例。所有数据对象都属于子类。 - PurkkaKoodari
我认为你的意思是可交换的,而不是可传递的。 - Nom1fan

0

如果我正确理解你的问题,你需要一种区分具有相同ID的同一类两个对象的方法。如果是这样,你可以使用toString()来获得对象的唯一表示,除非它们是字符串对象。当然,前提是你没有在基类中重写toString()方法。 例如:你可以将这个方法用于你提到的第三种情况。

if (this.toString()!= anObject.toString())
    return false;

不,我的问题是关于具有相同ID但是_不同_类的两个对象。 - PurkkaKoodari

-1

你可以使用Class.isInstance()方法来做到。在你的基类中,这样操作。

public static boolean isAnInstance(Object obj)
{
    return BaseClass.class.isInstance(obj);
}

然后你可以检查

if (BaseClass.isAnInstance(object))
{
    // Class of object is 'BaseClass' or
    // it extends the 'BaseClass'
}

希望这能有所帮助。

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接