Java instanceof 和 Class.isInstance()区别与应用

instanceof 关键字用于判断某个实例是否是某个类的实例化对象,形如:

String.class instanceof Class
"test" instanceof String

二、isInstance()方法

isInstance是Class类中的方法,也是用于判断某个实例是否是某个类的实例化对象,但是指向则相反。

但这样就带来一个疑问,为什么我们需要这个方法呢,官方文档如此解释:

Determines if the specified Object is assignment-compatible with the object represented by this Class.
This method is the dynamic equivalent of the Java language instanceof operator.
The method returns true if the specified Object argument is non-null
and can be cast to the reference type represented by this Class object without raising a ClassCastException.
It returns false otherwise.
加粗的部分就是主要的区别,主要突出一点:
  动态等效(dynamic equivalent)
但是这样并不容易理解,动态等效,虽然字面意思是运行时等效,一个例子会方便理解一些。
•  0 instance of String 本身就会报错 String.class.isInstance(0)则可行。

有了这点特性,我们可以在运行时判断两个类是否可以相互强转。

三、示例用法

public static void main(String[] args) {
        System.out.println("\"test\" instance of String:"+("test" instanceof String));
        System.out.println("\"test\" instance of Object:"+("test" instanceof Object));
        System.out.println("\"test\".getClass().isInstance(Object.class):"+("test".getClass().isInstance(Object.class)));
        System.out.println("\"test\".getClass().isInstance(String.class):"+("test".getClass().isInstance(String.class)));
        System.out.println("String.class.isInstance(Object.class):"+(String.class.isInstance(Object.class)));
        System.out.println("String.class.isInstance(String.class):"+(String.class.isInstance(String.class)));

System.out.println("String.class.isInstance(\"test\"):"+(String.class.isInstance("test")));


        System.out.println("Object.class.isInstance(\"test\"):"+(Object.class.isInstance("test")));
        Object object="ok";
        System.out.println("Double.class.isInstance(\"test\"):"+(Double.class.isInstance("test")));

Set<?> a=new HashSet<String>();
        Set<String> b=new HashSet<String>();
        System.out.println("a is b:"+aIsB(a,b));
    }
   

static boolean  aIsB(Object a,Object b){
        return a.getClass().isInstance(b);
    }

输出:

"test" instance of String:true
"test" instance of Object:true
"test".getClass().isInstance(Object.class):false
"test".getClass().isInstance(String.class):false
String.class.isInstance(Object.class):false
String.class.isInstance(String.class):false
String.class.isInstance("test"):true
Object.class.isInstance("test"):true
Double.class.isInstance("test"):false
a is b:true

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0cce42e6acb36e8f520235429c7a342c.html