Gilbeg
Gilbeg

Reputation: 751

Instantiate parameterized class using a field type of another class

I would like to use a type which I get from a class' field (using reflection) to instantiate a class with generics.
Note: I omitted the exceptions hoping for easy reading.

public class AClass   {
    class BClass<T>   {
        T aMemba;
    }

    public void AMethod()   {
        Class c = Class.forName("com.bla.flipper");
        Field f = c.getField("flipIt");

        // Here is my difficulty, I want to instantiate BClass with the type of
        // field 'f' but the compiler won't let me.
        Class typeClass = f.getType();
        BClass<typeClass> = new BClass<typeClass>();
    }
}

Is what I want to achieve reasonable? Any thought on how I can solve this problem?

Thanks!

Upvotes: 1

Views: 483

Answers (2)

Ben Schulz
Ben Schulz

Reputation: 6181

You can capture the type argument of the type of typeClass:

Field f = ...;
Class<?> typeClass = f.getType();
withClassCapture(typeClass);

private <T> void withClassCapture(Class<T> klazz) {
    BClass<T> instance = new BClass<T>();
    // ... do your thing
}

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Whatever you are trying to do is not reasonable because if you look at the following line:

BClass<typeClass> = new BClass<typeClass>();

typeClass is something that compiler should be aware of. But in your case it's only known in the runtime through reflection.

Compiler needs to erase T in BClass<T> and replace it with a concrete type which in your case is unknown at compile time so logically it's invalid.

Upvotes: 2

Related Questions