instanceof vs isInstance()

六眼飞鱼酱① 提交于 2019-12-12 11:07:44

问题


class A{

    public A(){
        System.out.println("in A");
    }
}

public class SampleClass{

    public static void main(String[] args) {
        A a = new A();

        System.out.println(A.class.isInstance(a.getClass()));
    }
}

Output:

false

Why is it false? Both A.class and a.getClass() should not return the same class!

And in which condition we will get true from the isInstance() method?


回答1:


Because a.getClass() returns Class<A>, but you should pass in an A:

System.out.println(A.class.isInstance(a));

If you have two Class instances and want to check for assignment compatibility, then you need to use isAssignableFrom():

System.out.println(A.class.isAssignableFrom(Object.class)); // false
System.out.println(Object.class.isAssignableFrom(A.class)); // true



回答2:


Because what a.getClass() returns has type Class<? extends A>, not A.

What A.class.isInstance tests is whether the passed object has type A.



来源:https://stackoverflow.com/questions/10944448/instanceof-vs-isinstance

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