java - 使用泛型的重载方法的莫名其妙的行为
问题描述
class My<T> {
void overloadMethod(String s) {
System.out.println("string");
}
void overloadMethod(Integer i) {
System.out.println("integer");
}
void overloadMethod(T t) {
System.out.println("t");
}
}
public class MyClass01 {
public static void main(String[] args) {
String o = "abc";
new My<String>().overloadMethod(o);
}
}
这给出了以下错误:
/MyClass01.java:20: error: reference to overloadMethod is ambiguous
new My<String>().overloadMethod(o);
^
both method overloadMethod(String) in My and method overloadMethod(T) in My match
where T is a type-variable:
T extends Object declared in class My
1 error
我期待“字符串”输出假设类型擦除将确保第三种方法是:
void overloadMethod(Object t) {
System.out.println("t");
}
我在这里想念什么?
谢谢。
解决方案
通过将泛型 实例class MyClass<T>
化为特定的参数化类型new My<String>().overloadMethod(o);
,您已经有效地声明了两个具有相同签名的方法:overloadMethod(String s)
.
这就是编译器错误试图告诉你的:“<em> error: reference to overloadMethod is ambiguous
”。
„<em>...我在这里错过了什么?...</em>“</p>
因为您说:“<em>我期待“字符串”输出”,听起来您错误地假设您的声明以class My<T>
某种方式使您的非泛型方法overloadMethod(String s)
具有参数多态性的能力。它没有。
推荐阅读
- vuejs2 - 通过数组移动的Vue组件问题
- python - Windows 10 上 python 3.8 中的 PyCairo Pip 安装失败
- c++ - 使用 Clang++ 有没有办法将文件包含为命名空间等?
- c++ - 如何在 cmake 库中包含 libcurl
- ngxs - NGXS:如何让 RouteHandler 工作?
- python - 使用 Google Cloud Vision API 的分段错误
- c# - c# 从 API 中清除 URL 字符串
- javascript - 为什么我继续收到这个 TypeError: expect is not a function
- java - 在不知道是哪一个的情况下实例化一个参数化的 java 类
- logging - 如何配置 Kafka 服务器日志记录,以便无需重新启动即可更改日志级别?