请看下面代码:
public static void method(List<String> list){//类型擦除 变成原生类型List list
System.out.println("method(List<String> list)");
}
public static void method(List<Integer> list){
System.out.println("method(List<Integer> list)");
}
}
这个题目是一个考察泛型的题目。Java里面,泛型实际上是“伪泛型”,编译不通过
IDE会提示我们下面的错误:
Erasure of method method(List<String>) is the same as another method in type GenericTypes
在java中,泛型只存在于源代码之中,在编译过后的代码中,泛型信息已经被“擦除”了。上面的代码被编译之后的样子应该是下面类似的代码:
public class GenericTypes {
public static void method(List<T> list){
System.out.println("method(List<String> list)");
}
public static void method(List<T> list){
System.out.println("method(List<Integer> list)");
}
}
两个函数具有相同的签名,当然编译器会拒绝为我们编译这样的代码。
请再看下面一个例子
看下面代码:
public class GenericTypes2 {
public static String method(List<String> list){//类型擦除 变成原生类型List list
return "string";
}
public static Integer method(List<Integer> list){
return 1;
}
}
这段代码能正常编译吗?
熟悉class文件结构的人能知道,这段代码能正常编译(重载成功了!)。而且还能正常执行
【请注意 重载成功 仅限于jdk1.6及以下,jre1.7 是编译不通过的 】
原因在于,虽然函数的返回值不参与函数签名的生成,但是在class文件格式之中,只要描述符不完全一致的两个方法就能共存于一个class文件中。