java关键字 instanceof

instanceof是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例。

用法为:

boolean result = obj instanceof Class  //obj 为一个对象,Class 表示一个类或者一个接口,
                                       // 当 obj 为 Class 的对象,或者是其直接或间接子类,或                    
                                       //者是其接口的实现类,结果result 都返回 true,否则返回false。

注:编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。

例1:instanceof 运算符只能用作对象的判断,不能用于基本数据类型

int i = 0;
System.out.println(i instanceof Integer);//编译不通过
System.out.println(i instanceof Object);//编译不通过

例2:如果 obj 为 null,那么将返回 false

System.out.println(null instanceof Object);//false

例3:如果obj是对象,则返回true

Integer integer = new Integer(1);
System.out.println(integer instanceof  Integer);//true

例4:如果obj为接口实现类,则返回为true

ArrayList arrayList = new ArrayList();//ArrayList实现了List接口
System.out.println(arrayList instanceof List);//true

例5:obj为class的直接或间接类

Person p1 = new Person();//父类
Person p2 = new Man();//子类(多态)
Man m1 = new Man();//子类
System.out.println(p1 instanceof Man);//false,因为p1不是Man的子类
System.out.println(p2 instanceof Man);//true
System.out.println(m1 instanceof Man);//true

例6:instanceof关键字与包装类结合

解析:

collection类型的集合(ArrayList,LinkedList)只能装入对象类型的数据,该题中装入了0,是一个基本类型,但是JDK5以后提供了自动装箱与自动拆箱,所以int类型自动装箱变为了Integer类型。编译能够正常通过。

将list1的引用赋值给了list2,那么list1和list2都将指向同一个堆内存空间。instanceof是Java中关键字,用于判断一个对象是否属于某个特定类的实例,并且返回boolean类型的返回值。显然,list1.get(0)和list2.get(0)都属于Integer的实例

猜你喜欢

转载自blog.csdn.net/guanmao4322/article/details/84174405