package org.my.java;
public class TestTypeVariable {
static <T,A extends T> void typeVarType(T t, A a){
System.out.println(a.getClass());
System.out.println(t.getClass());
}
public static void main(String[] s){
int i= 1;
typeVarType("string", i);
}
}
运行后输出如下:
class java.lang.Integer
class java.lang.String
当 A
的上界已经是 String
时,它怎么可能是 Integer
类型?
请解释一下。
最佳答案
这里有两件事:
- 对于“错误的”输入有一个简单的解决方案:T 不是字符串而是对象。 Integer 扩展了 Object。但请注意:这仅适用于 Java8 的“增强型”类型推断功能。使用 Java7,您的输入将无法编译!
- 您的误解:
getClass()
发生在运行时,因此返回传递的对象的特定类 - 与编译器在编译时对泛型的看法无关时间。
关于java - 类型变量如何允许类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46400480/