Java Generics & Reflection

北慕城南 提交于 2020-01-05 10:33:41

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5756081/java-generics-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!