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。

  • 相关阅读:
    88250 的“一分钟想法”
    88250 的“一分钟想法”
    有关在对话框上创建视图上的再探索
    jmap命令(Java Memory Map) 51CTO.COM
    要么滚回家里去,要么就拼
    悲观的思考,乐观的生活.我们既需要思考的深度,也需要生活的温度!
    对研发经理这一岗位的个人理解
    Linux Soho 兼 职 系统工程师 Email: yufeixiaoyu@gmail.com
    9月1日机器学习与自然语言处理精品班开班现场_培乐资讯_北京培乐园科技咨询有限公司
    简单的Memory leak跟踪
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3246877.html
Copyright © 2011-2022 走看看