微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在下面的代码中,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
   }
}

原文地址:https://www.jb51.cc/java/128011.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐