做网站需要企业,山东专业网站建设公司哪家好,养生门户网站源码,腾讯企点怎么解绑手机号instanceof 是 Java 的一个二元操作符#xff0c;类似于 #xff0c;#xff0c; 等操作符#xff0c; 是 Java 的保留关键字。左边是对象#xff0c;右边是类#xff1b;当对象是右边类或者子类所创建的对象时#xff0c;返回true#xff0c;否则返回false。 … instanceof 是 Java 的一个二元操作符类似于 等操作符 是 Java 的保留关键字。左边是对象右边是类当对象是右边类或者子类所创建的对象时返回true否则返回false。 boolean result obj instanceof Class
1、obj 必须为引用类型不能是基本类型
int i 0;
System.out.println(i instanceof Integer);//编译不通过
System.out.println(i instanceof Object);//编译不通过
instanceof 运算符只能用作对象的判断。
2、如果 obj 为 null那么将返回 false。
System.out.println(null instanceof Object);//false
3、obj 为 class 类的实例对象
Integer a new Integer(1);
System.out.println(a instanceof Integer);//true
4、obj 为 class 接口的实现类
我们知道集合中有个上层接口 List其有个典型实现类 ArrayList
public class ArrayListE extends AbstractListEimplements ListE, RandomAccess, Cloneable, java.io.Serializable
所以我们可以用 instanceof 运算符判断 某个对象是否是 List 接口的实现类如果是返回 true否则返回 false
ArrayList arrayList new ArrayList();
System.out.println(arrayList instanceof List);//true 或者反过来也是返回 true
List list new ArrayList();
System.out.println(list instanceof ArrayList);//true
5、obj 为 class 类的直接或间接子类
我们新建一个父类 Person.class然后在创建它的一个子类 Man.class
public class Person {}
public class Man extends Person{} 测试
Person p1 new Person();
Person p2 new Man();
Man m1 new Man();
System.out.println(p1 instanceof Man);//false
System.out.println(p2 instanceof Man);//true
System.out.println(m1 instanceof Man);//true