Comparing Class Types in Java

前端 未结 8 2043
不知归路
不知归路 2020-12-14 06:07

I want to compare the class type in Java.

I thought I could do this:

class MyObject_1 {}
class MyObject_2 extends MyObject_1 {}

public boolean funct         


        
8条回答
  •  眼角桃花
    2020-12-14 06:31

    If you don't want to or can't use instanceof, then compare with equals:

     if(obj.getClass().equals(MyObject.class)) System.out.println("true");
    

    BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

    • the classes have the same short name but are defined in different packages
    • the classes have the same full name but are loaded by different classloaders.

提交回复
热议问题