Java - 接口 -instsnceof

Java - interface -instsnceof

这怎么可能合法? A 不是由 Intf 实现的。那么这样使用怎么可能合法呢?

    interface Intf {
}

class A{
}

class B{}

class Test {    
    public static void main(String[] args) {
        A obj = new A();
        System.out.println(obj instanceof Intf); //Legal - no any errors, just output false
        System.out.println(obj instanceof B);  // Illegal - compile error
    }
}

JLS 15.20.2 状态:

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error (§15.16), 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.

在这种情况下 (Intf) obj 不是编译时错误,因为 JLS 15.16 指出:

If the compile-time type of the operand cannot be converted by casting conversion (§5.5) to the target type specified by the cast operator, then a compile-time error occurs.

那么为什么转换不是编译错误?

因为 obj 的静态类型是 A,实际可能是 AA 的任何子类。 A 的子类可以 实现 Intf !!

现在我们可以看到在这种情况下这是不可能的,因为 obj 已经使用对 A 实例的引用进行了初始化....但是不允许类型检查器使该逻辑推理。 (或者至少如果是这样,它只能将其视为警告而不是错误。)