确定两个Java对象是否属于同一个类 [英] Determine if two Java objects are of the same class

查看:1028
本文介绍了确定两个Java对象是否属于同一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做相当于

if ( object1.class == object2.class )
{
    //do something
}  

这当然不起作用,我用什么方法可以忽略?

which of course doesn't work, what method am I overlooking?

推荐答案

如果他们来自完全相同的类:

If they're from the exact same class:

boolean result = object1.getClass().equals( object2.getClass());

现在,如果它们是兼容的类(如果一个是另一个的后代类):

Now if they are compatible classes (if one is of a descendent class to the other):

HashMap<String,Object> hashMap = new HashMap<String,Object>();
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<String,Object>();
boolean result = hashMap.getClass().isAssignableFrom( linkedHashMap.getClass() );

由于LinkedHashMap是HashMap的子类,因此结果变量为true,所以这对你来说可能更好,因为它会找到确切的和子类匹配。

As LinkedHashMap is a subclass of HashMap this result variable will be true, so this might probably be better for you as it's going to find exact and subclass matches.

另外,你应该避免在变量上使用.class,因为它可能不会给你正确的结果,例如:

Also, you should avoid using ".class" on variables, as it might not give you the correct result, example:

Object someText = "text value";
System.out.println( someText.class.getName() ); //this will print java.lang.Object and not java.lang.String

当你是使用.class你可以访问变量static属性而不是对象本身的类。

When you're using ".class" you're acessing the variable static property and not the class of the object itself.

这篇关于确定两个Java对象是否属于同一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆