See if two object have the same type

后端 未结 5 1814
终归单人心
终归单人心 2021-02-04 02:00

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-c         


        
5条回答
  •  情歌与酒
    2021-02-04 02:39

    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.

提交回复
热议问题