Java 泛型和反射
这可能是一个基本问题,但是我可以这样做吗:
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;
}
}
显然,上面的代码不正确,因为 myClass 是 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你不能那样做。有什么意义?泛型为您提供编译时类型检查,如果该类直到运行时才知道,您将不会获得任何结果。
No, you can't do that. What's the point? Generics give you compile-time type checking and if the class isn't known until runtime, you don't gain anything.
Java中的泛型仅用于编译时的静态类型检查;类型检查后通用信息将被丢弃(了解类型擦除 )因此
SomethingSimple
在运行时实际上只是一个SomethingSimple
当然,您不能对运行时才知道的类型进行完整的类型检查。编译器必须知道该类型,这就是为什么您必须使用实际类型名称而不是
Class
变量作为泛型类型参数。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 aSomethingSimple<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.泛型是保证类型安全的编译时机制,反射是运行时机制。你的意思是,“我在编译时不知道 T 的类型是什么,但我想要编译时类型安全”(这没有多大意义)。换句话说,java 在运行时删除 T 的类型并将其存储为对象......因此 T 的类型(就泛型而言)不再重要。
但实际上,您似乎想要一个依赖注入容器,例如 spring 或 google guise。
Generics is a compile time mechanism to ensure type safety, and reflection is a runtime mechanism. What you're saying is, "I don't know at compile time what the type of T is but I want compile time type safety" (which doesn't make much sense). To put it another way, java erases the type of T at runtime and stores it as an Object...so the type of T (as far as generics are concerned) no longer matters.
But really it seems like you want a dependency injection container, like spring or google guise.