其中SomethingSimple是一个简单的 泛型类:
class SomethingSimple< T> { T值; SomethingSimple(){} public void setT(T val) { value = val; } public T getT() {返回值; $ / code>显然,上面的代码是不正确的,因为myClass是Class类型的对象,并且需要一个类。问题是如何实现这一点。我阅读了泛型反射的其他主题,但他们关心的是泛型类是如何知道类型的。
解决方案使用Java中的泛型仅在编译时进行静态类型检查;类型检查后通用信息将被丢弃(请阅读类型擦除 ),所以在运行时, SomethingSimple< Foo> 实际上只是一个 SomethingSimple< Object> 。 $ b
当然,你不能对直到运行时才知道的类型进行补全时间类型检查。类型必须为编译器所知,这就是为什么你必须使用实际类型名称而不是 Class 变量作为泛型类型参数。
this probably is a basic question, but can I do something like this:
Class myClass = Class.forName("Integer"); SomethingSimple<myClass> obj;Where SomethingSimple is a very simple generic class:
class SomethingSimple<T> { T value; SomethingSimple() {} public void setT(T val) { value = val; } public T getT() { return value; } }Obviously, the code above is not correct, since myClass is an object of type Class, and a class is required. The question is how can this be achieved. I read the other topics about Generics Reflection, but they concerned how the generic class knows the type.
解决方案Generics in Java are used only for static type checking at compile time; the generic information is discarded after type checking (read about type erasure) so a SomethingSimple<Foo> is effectively just a SomethingSimple<Object> at runtime.
Naturally, you can't do comple-time type checking on a type that isn't known until runtime. The type has to be known to the compiler, which is why you have to use an actual type name rather than a Class variable as the generic type parameter.
更多推荐
Java泛型&反射
发布评论