See if two object have the same type

巧了我就是萌 提交于 2019-12-04 08:19:20

问题


Let's say that I have a class A, and that B,C,D are derived from A.
If I want to know what's the type of an object referenced, I can declare:

// pseudo-code
if(obj instanceof B)
    < is B>
else if(obj instanceof C)
    < is C>
else
    <is D>

This because I am sure that the classes derived from A are only B,C and D.
But what if I want just to check that two references point to the same kind of object?
So something like:

if(obj1 instanceof obj2)
   <do something>

But of course the syntax is wrong.How to check this without one thousand if-else?


回答1:


You mean something like

obj1.getClass().equals(obj2.getClass())

This should return true just if both obj1 and obj2 are of the same specific class.

But this won't work if you are comparing A with B extends A. If you want equality that returns true even if one is a subtype of another you will have to write a more powerful comparison function. I think that you can do it by looping with getSuperClass() to go up the hierarchy tree.

I think a simple solution can be also to do A.getClass().isAssignableFrom(B.getClass()), assuming that B extends A.




回答2:


You could do

if (obj1.getClass() == obj2.getClass()) { ... }



回答3:


Something like this:

if(classA.getClass().getName().equals(classB.getClass().getName()))
     <do something>



回答4:


Since B, C and D are subclasses of A, and you want to do something with these classes, I wouldn't use the instanceOf operator. This one's only useful for when there's no other way.

You could better override the super methods and/or variables, so you can use all the objects the same, tough they will do something different (for example printing it's own type).




回答5:


instanceof needs to point towards a class, not another object. To check that two objects both come from the same type of object do something to the following ..

if((obj1 instanceof ClassName) && (obj2 instanceof ClassName)) {
  do whatever
}


来源:https://stackoverflow.com/questions/10162802/see-if-two-object-have-the-same-type

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