我所做的就是了解Generics在Java中的工作原理.我写了以下代码:
public class Test { public static void main(String... args) throws Exception{ Foo o = new Foo(new Integer(5)); o.fun(); } } class Foo { 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而不显示错误/异常.
第二件事是,当我写信t = 9;
时function fun()
,它显示:
incompatible types required: T found: java.lang.Integer
泛型类如何工作以及如何使用它们?
非常感谢您的回复!!