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
   }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...