gpt4 book ai didi

java - 为什么 "array instanceof Iterable"不能用 Java 编译?

转载 作者:太空狗 更新时间:2023-10-29 22:45:58 24 4
gpt4 key购买 nike

Object[] array = new Object[]{};
System.out.println((array instanceof Serializable));//passed
System.out.println((array instanceof Cloneable));//passed

此代码编译并运行。输出是:

true
true

但是,这段代码无法编译:

System.out.println((array instanceof Iterable));//not passed

Eclipse 编译器报告:

Incompatible conditional operand types Object[] and Iterable

我发现当使用操作instanceof时,只能在interfaceSerializableCloneable之间比较数组。谁能告诉我为什么?

最佳答案

根据JLS, Java SE 7 edition , § 15.20.2 (类型比较运算符 instanceof):

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.

和§ 15.16 (Cast Expressions) 声明:

It is a compile-time error if the compile-time type of the operand may never be cast to the type specified by the cast operator according to the rules of casting conversion (§5.5).

最后,§ 5.5.1 (引用类型转换)状态:

Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules.

[...]

If S is an array type SC[], that is, an array of components of type SC:

  • If T is an interface type, then a compile-time error occurs unless T is the type java.io.Serializable or the type Cloneable (the only interfaces implemented by arrays).

因此,Java 要求您测试数组类型是否是 java.lang.Iterable 的实例会导致编译时错误。

如果你想让它工作(总是返回false),你可以先把数组转换成Object,像这样:

System.out.println((((Object)array) instanceof Iterable));

关于java - 为什么 "array instanceof Iterable"不能用 Java 编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11354958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com