我所做的只是了解泛型在 Java 中的工作原理。 我写了下面的代码:
public class Test {
public static void main(String... args) throws Exception{
Foo o = new Foo<Integer>(new Integer(5));
o.fun();
}
}
class Foo<T> {
private T t;
public Foo(T t) throws InstantiationException, IllegalAccessException{
System.out.println("1. T is "+t.getClass());
this.t = (T)"test";
System.out.println("2. T is "+t.getClass());
}
void fun(){
System.out.println("3. T is "+t.getClass()+" t = "+t);
}
}
输出是
1. T is class java.lang.Integer
2. T is Still class java.lang.Integer
3. T is class java.lang.String t = test
我的问题是为什么这会将 Class 从 Integer 更改为 String 而没有显示错误/异常。
第二件事是,当我在 function fun()
中编写 t = 9;
时,它显示:
incompatible types
required: T
found: java.lang.Integer
泛型类如何工作以及如何使用它们?
非常感谢您的回复!!
最佳答案
您已使用 no upper bound 声明了一个泛型.替换无界泛型
是Object
本身
这意味着,当生成类文件时,您的 Foo<T>
类看起来像这样
class Foo {
private Object t;
public Foo(Object t) throws InstantiationException, IllegalAccessException{
System.out.println("1. T is "+t.getClass());
this.t = (Object)"test";
System.out.println("2. T is "+t.getClass());
}
void fun(){
System.out.println("3. T is "+t.getClass()+" t = "+t);
}
}
这是因为泛型只是为了确保编译时类型安全。在运行时它们被删除
考虑到这一点
this.t = (Object)"test";
是一个有效的陈述,因为 Object
是所有类的父类(super class)并且this.t
然后变成String
2. T is Still class java.lang.Integer
的原因,
- 在这里
t
是一个构造函数的参数并且该参数仍然指向Integer
(不被覆盖) - 并且参数优先于
this.t
关于java - Class T 如何以及何时从 Integer 更改为 String 而不是显示错误/异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20279446/