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

转载注明原文:java – 为什么这个instanceof代码工作并且不会导致编译时错误? - 代码日志