zoukankan      html  css  js  c++  java
  • Java Instanceof

    Java Instanceof

    Instanceof是一个非常简单的运算符,前一个操作通常是一个引用类型的变量,后一个操作数通常是一个类(也可以是接口,可以把接口理解成一种特殊的类),它用于判断前面的对象是否是后面的类或其子类,实现类的实例。如果是,返回true,否则,返回false。

    public class InstanceTest {

         public static void main(String[] args){

           Object hello = "Hello";

           System.out.println(hello instanceof Object);

           System.out.println(hello instanceof String);

           System.out.println(hello instanceof Math);

           System.out.println(hello instanceof Comparable);

           String str = "hello";

           System.out.println(str instanceof Object);

           //System.out.println(strinstanceof Math);

           System.out.println(hello instanceof java.io.Serializable);

         }

    }

    Output:

    true

    true

    false

    true

    true

    true

    System.out.println(strinstanceof Math);则编译错误是因为instanceof运算符有一个限制,编译时类型必须是如下3种情况:

    要么与后面的类相同;要么是后面类的子类;要么是后面类型的子类。

    如果前面操作数的编译时类型与后面的类型没有任何关系,程序将没发通过编译。

    在运行阶段,被转型变量所引用对象的实际类型必须是目标类型的实例,或者是目标类型的子类,实现类的实例,否则在运行时将引发ClassCastException异常。

    public class InstanceTest {

         public static void main(String[] args){

           Object hello = "Hello";

           String objStr = (String)hello;

           System.out.println(objStr);

           Object objPri = new Integer(5);

           String str = (String)objPri;

           String s ="Java";    

         }

    }

    Exceptionin thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

    Hello

          at InstanceTest.main(InstanceTest.java:8)

    无法从Integer转换成String类型。

     

     

    public class InstanceTest {

         public static void main(String[]args){

           String s = null;

           System.out.println(s instanceof String);

         }

    }

    False

    S定义为null,虽然null可以作为所有引用类型变量的值,但对于s引用变量而言,它实际并未引用一个真正的String对象,因此程序输出false。

  • 相关阅读:
    Linux 系统下 “账户管理”
    gulp添加版本号解决缓存问题
    vue3.0的proxy浅析内层绑定原理
    rem用font-size布局与easyui的datagrid通用,出现table不显示
    堆与栈 | 对象深浅拷贝
    vue双向绑定原理值Object.defineProperty
    bootstrap模态框不出,只出现黑色蒙层bug
    Appdelegate 导航操作
    CLLocationManager 位置定位
    导航创建
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3246877.html
Copyright © 2011-2022 走看看