我尝试深入研究 Java 泛型,但遇到了以下示例代码描述的问题。
public static void test(Object o) {
System.out.println("Hello Object!");
}
public static void test(Integer i) {
System.out.println("Hello Integer!");
}
public static <T> void test(Collection<T> col) {
for (T item : col) {
System.out.println(item.getClass().getSimpleName());
test(item);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Collection<Integer> ints = new ArrayList<>();
ints.add(1);
test(ints);
}
样本的输出是
Integer
Hello Object!
所有类型显然在编译时都是已知的。据我所知,Java 只保存每个方法的一个编译副本(与 C++ 不同),并且由于没有给出关于参数 T 的其他约束,它被迫调用通用对象实现。
我的问题是 - 有没有什么方法可以在不重载 Collection<Integer>
的测试方法的情况下为整数调用“Hello Integer”方法?并且不使用运行时类型检查?
最佳答案
这是不可能的。由于类型删除类型 Collection<T>
将解析为类型 Collection<Object>
. Erasure of Generic Methods
关于Java 泛型 - 从泛型类型调用特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27339388/