Determine if two Java objects are of the same class

核能气质少年 提交于 2019-12-18 12:43:16

问题


I am attempting to do the equivalent of

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

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


回答1:


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() );

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.

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

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




回答2:


You're missing the getClass() method,

if (object1.getClass().equals(object2.getClass())) 
{ 
    // do something 
}



回答3:


You can use this:

if (object1.getClass().equals(object2.getClass())) {
    //do something
}



回答4:


object1.getClass() == object2.getClass()



回答5:


you have to use the getClass() method.

try:

if(object1.getClass() == object2.getClass())
   //do something



回答6:


You're looking for the getClass method, defined in java.lang.Class.

(Source: http://download.oracle.com/javase/7/docs/api/java/lang/Class.html)



来源:https://stackoverflow.com/questions/6821810/determine-if-two-java-objects-are-of-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!