gpt4 book ai didi

java - 功能或错误 :Why does this Java code compile?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:08 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Is this valid Java?

我惊讶地发现下面的 Java 类可以编译。它有几个方法,具有相同的名称、参数数量和以下类型删除类型的参数。然而,它在使用各种版本的 Sun JDK 1.6 编译器的 Windows 上按预期编译和工作。因此,如果这是一个错误,它已经存在多年了......

它还可以使用多个版本的 Eclipse 进行编译,但不能使用 Eclipse 3.6 附带的编译器进行编译

此外,调用代码按预期工作 - 即。调用代码中没有关于模棱两可的方法的错误。

如果您遍历 ErasureExample.class.getMethods() 返回的方法,它们都存在......

根据 JLS,如果方法具有“覆盖等效”签名将是非法的 - 严格来说它们没有,因为 Collection,Collection 和 Collection 都不是覆盖等效的......如果是这样的话 Eclipse 是错了,JDK 正确...

特性还是错误?它应该编译吗?

/**
* Demonstrates that a class with methods that differ only by return type can exist.
* Section 8.4 of the JLS suggests this is an error IFF the methods had
* override equivalent signatures, which they dont''
*
*
* From JLS 8.4...

* It is a compile-time error for the body of a class to declare as members two methods
* with override-equivalent signatures (§8.4.2) (name, number of parameters, and types
* of any parameters).
*
* Should it compile?
*/
public class ErasureExample {
// note the single Collection<Integer> argument...
public static int[] asArray(Collection<Integer> vals) {
if (vals == null)
return null;

int idx = 0;
int[] arr = new int[vals.size()];
for (Integer i : vals) {
arr[idx] = i==null? 0 : i.intValue();
idx++;
}
return arr;
}

// same method name as above, type differs only by generics.... surely this violates 8.4 of JLS...
public static long[] asArray(Collection<Long> vals) {
if (vals == null)
return null;

int idx = 0;
long[] arr = new long[vals.size()];
for (Long i : vals) {
arr[idx] = i==null? 0 : i.longValue();
idx++;
}
return arr;
}

// same method name as above, type differs only by generics.... surely this violates 8.4 of JLS...
public static boolean[] asArray(Collection<Boolean> vals) {
if (vals == null)
return null;

int idx = 0;
boolean[] arr = new boolean[vals.size()];
for (Boolean b : vals) {
arr[idx] = b==null? false : b.booleanValue();
idx++;
}
return arr;
}

}

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