gpt4 book ai didi

java - 为什么对数组组件赋值的类型检查是在运行时完成的?

转载 作者:行者123 更新时间:2023-11-30 01:54:27 25 4
gpt4 key购买 nike

我正在阅读Effective java第28条,其中作者写道

The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element type at runtime.

但是为什么在运行时呢?例如,考虑两个类,其中 A 是 B 的父级

public static void main(String[] args) {
A[] array = new B[10];
array[0] = new A();
}

此代码抛出 ArrayStoreException。对我来说,编译器似乎可以识别出错误。那么为什么编译器会让它通过呢?是因为 JLS 不希望编译器那么智能(慢)吗?

JLS 10.5 For an array whose type is A[], where A is a reference type, an assignment to a component of the array is checked at run time to ensure that the value being assigned is assignable to the component.

现在我的理解是

  • 在编译时(以及运行时)上例中的数组变量的类型为 A[]
  • 编译器的职责是确保仅将 A[] 或 A[] 的某些子类型分配给数组变量。
  • 数组的组成部分(array[0])也是如此,编译器只会检查分配的值是否为 A 或 A 的某些子类型。

当 A() 分配给 array[0] 时,编译器为什么不考虑实际的数组对象 (B[10])。 是因为编译器没有可用的信息吗?

最佳答案

To me, it seems that error could have been identified by the compiler.

嗯,不;编译器无法确定运行时数组的实际类型。

让我们举一个简单的例子,

array = myRandomFunction()>0 ? new A[10] : new B[10];

那么 array 的实际类型可以是 A[]B[] ,编译器也无能为力。

<小时/>

如果你想一下;这与 NullPointerException 发生的情况类似:编译器不会提示以下内容(即使 if 总是在运行时抛出)

Object a=null;
a.toString();

关于java - 为什么对数组组件赋值的类型检查是在运行时完成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949346/

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