Java Generics & Reflection

2019-08-04 19:24发布

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.

3条回答
We Are One
2楼-- · 2019-08-04 19:35

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.

查看更多
Viruses.
3楼-- · 2019-08-04 19:40

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.

查看更多
我只想做你的唯一
4楼-- · 2019-08-04 19:42

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.

查看更多
登录 后发表回答