Java关键字instanceof的两种用法实例


instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。
 
举个例子:

复制代码 代码如下:

public interface IObject {
}

public class Foo implements IObject{
}

public class Test extends Foo{
}

public class MultiStateTest {
        public static void main(String args[]){
                test();
        }

        public static void test(){
                IObject f=new Test();
                if(f instanceof java.lang.Object)System.out.println("true");
                if(f instanceof Foo)System.out.println("true");
                if(f instanceof Test)System.out.println("true");
                if(f instanceof IObject)System.out.println("true");
        }
}

输出结果:

复制代码 代码如下:

true
true
true
true

 
另外,数组类型也可以使用instanceof来比较。比如
复制代码 代码如下:

String str[] = new String[2];

则str instanceof String[]将返回true。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3