Abh*_*nav 5 java generics overloading type-erasure erasure
以下代码提供编译错误,错误"重复方法"
static int test(int i){
return 1;
}
static String test(int i){
return "abc";
}
Run Code Online (Sandbox Code Playgroud)
这是预期的,因为重载方法具有相同的签名并且仅在返回类型方面不同.
但是下面的代码编译好了警告:
static int test1(List<Integer> l){
return 1;
}
static String test1(List<String> l){
return "abc";
}
Run Code Online (Sandbox Code Playgroud)
因为,我们知道Java Generics在Erasure上运行,这意味着在字节码中,这两种方法都具有完全相同的签名,并且与返回类型不同.
更令我惊讶的是,以下代码再次出现编译错误:
static int test1(List<Integer> l){
return 1;
}
static String test1(List l){
return "abc";
}
Run Code Online (Sandbox Code Playgroud)
如果有重复的方法,第二个代码如何工作正常而不会给出任何编译错误?
解析重载方法是在编译时而不是运行时完成的,因此 Java 编译器会知道第二个示例中两者之间的区别。在你的第三个例子中,问题是 aList<Integer>也是 a List,所以如果你传入 a ,它不知道要使用哪个List<Integer>。
| 归档时间: |
|
| 查看次数: |
8723 次 |
| 最近记录: |