1、前言
1.一、instanceof
是 Java 的保留关键字,一个二元操做符(和==,>,<是同一类东东)1.二、
做用:测试它左边的对象是不是它右边的类的实例1.三、
返回值:返回 boolean 的数据类型。instanceof
用法详解及instanceof是什么意思,须要的朋友参考下吧2、instanceof 的说明、解释
2.一、
说明: instanceof
左边操做元显式声明的类型与右边操做元必须是同种类或有继承关系, 即位于继承树的同一个分支上, 不然会编译出错 !2.二、
demo2.2.1_demo01_:测试
double obj = 1; if (obj instanceof Double) System.out.println("true"); //无输出-->不成立
编译信息: Incompatible conditional operand types double and Double错误code
2.2.2_demo02_:对象
String obj = 1.0 + ""; if (obj instanceof Double) System.out.println("true"); //无输出:
编译信息:Incompatible conditional operand types String and Double" 错误继承
2.2.3_demo03_:token
if(null instanceof Object) System.out.println("true"); else System.out.println("false"); //输出:false String obj = null; if (obj instanceof Object){ System.out.println("true"); else System.out.println("false"); //输出:false
分析:null用操做符instanceof测试任何类型时都是返回false的接口
2.2.4_demo04_:编译器
String obj = null; if (obj instanceof null) System.out.println("true"); else System.out.println("false");
编译信息:Syntax error on token "null", invalid ReferenceType" 标记"null"上的语法错误,无效引用类型it
2.2.5_demo05_:前方高能,务必仔细阅读!!!io
class Student {} public class Test { public static void main(String[] args){ //第1组 System.out.println(new Student() instanceof String); //编译时错误 System.out.println(new Student() instanceof Exception); //编译时错误 System.out.println(new Student() instanceof Object); //输出时true //第2组 System.out.println(new Student() instanceof List); //输出false System.out.println(new Student() instanceof List<?>); //输出false System.out.println(new Student() instanceof List<String>); //编译错误 System.out.println(new Student() instanceof List<Object>); //编译错误 //第3组 System.out.println(new String() instanceof List); //编译错误 System.out.println(new String() instanceof List<?>); //编译错误 //第4组 System.out.println(null instanceof Object); //输出错误,同demo03 } }
分析:编译
对于第2组:
疑惑1:为何用student()测试String时编译报错,测试List的时编译经过
疑惑2:Student已经肯定类型了啊,List类型也是肯定的啊,为何可以编译经过呢,而String却不行呢?``
String、Integer、Long
等都是最终类,他们的处理相似于编译器对常量的处理,故而能够经过编译final
关键字的时候,其表现就跟String、Integer、Long
这些最终类测试instanceof表现的同样了。3、instanceof 的用法
result = object instanceof class
result
:布尔类型值object
:类的对象class
: 对象类4、综述