加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么这个instanceof代码工作并且不会导致编译时错误?

发布时间:2020-12-15 02:51:26 所属栏目:Java 来源:网络整理
导读:在下面的代码中,x的类型是I(虽然x也实现了J但在编译时不知道),为什么(1)处的代码不会导致编译时错误. 因为在编译时只考虑引用的类型. public class MyClass { public static void main(String[] args) { I x = new D(); if (x instanceof J) //(1) System.ou
在下面的代码中,x的类型是I(虽然x也实现了J但在编译时不知道),为什么(1)处的代码不会导致编译时错误.
因为在编译时只考虑引用的类型.
public class MyClass {
    public static void main(String[] args) {
        I x = new D();
        if (x instanceof J) //(1)
            System.out.println("J");
    }
}

interface I {}

interface J {}

class C implements I {}

class D extends C implements J {}

解决方法

instanceof用于运行时确定对象的类型.您正在尝试确定在程序运行时x是否真的是J类型的对象,因此它会进行编译.

您是否认为它会导致编译时错误,因为您认为编译器不知道x的类型?

编辑

正如Kirk Woll评论的那样(感谢Kirk Woll!),如果你正在检查x是否是具体类的实例,并且编译器可以确定x的类型,那么在编译时会出现错误.

从Java语言规范:

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error,then the instanceof relational expression likewise produces a compile-time error. In such a situation,the result of the instanceof expression could never be true.

作为一个例子:

import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

class SerializableClass implements Serializable
{
   private writeObject(ObjectOutputStream out) {}
   private readObject(ObjectInputStream in) {}
}

public class DerivedSerializableClass extends SerializableClass
{
   public static void main(String[] args)
   {
      DerivedSerializableClass dsc = new DerivedSerializableClass();

      if (dsc instanceof DerivedSerializableClass) {} // fine
      if (dsc instanceof Serializable) {} // fine because check is done at runtime
      if (dsc instanceof String) {} // error because compiler knows dsc has no derivation from String in the hierarchy

      Object o = (Object)dsc;
      if (o instanceof DerivedSerializableClass) {} // fine because you made it Object,so runtime determination is necessary
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读