查看两个对象是否具有相同的类型 [英] See if two object have the same type
问题描述
假设我有一个A类,B,C,D是从A派生的。
如果我想知道引用的对象的类型是什么,我可以声明:
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>
这是因为我确信从A派生的类只有B,C和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>
但当然语法错误。如果没有一千个if-else怎么检查呢?
But of course the syntax is wrong.How to check this without one thousand if-else?
推荐答案
你的意思是
obj1.getClass().equals(obj2.getClass())
这应该返回true obj1
和 obj2
属于同一特定类别。
This should return true just if both obj1
and obj2
are of the same specific class.
但是,如果你将 A
与进行比较,那么这将不起作用.B扩展A
。如果你想要等于返回true,即使一个是另一个的子类型,你将不得不编写一个更强大的比较函数。我认为您可以通过使用 getSuperClass()
循环来上升层次结构树。
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.
我认为一个简单的解决方案也可以做 A.getClass()。isAssignableFrom(B.getClass())
,假设 B扩展A
。
I think a simple solution can be also to do A.getClass().isAssignableFrom(B.getClass())
, assuming that B extends A
.
这篇关于查看两个对象是否具有相同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!