SG Tech Edge
SG Tech Edge

Reputation: 507

How to create a parametrised type in java with a type variable?

The question title could be misleading, but I dont know how to summarise better what I want to acomplish. So please read through this body to undestand what I want to achive.

I have a method with a type parameter which gets some Class (eg MyClass). I need to create a Type of List and return it.

I thought this code would solve my problem. But the actual behaviour suprised me.

    public <T> Type getListClass(Class<T> cls) {
    Type type = new TypeToken<ArrayList<T>>() {}.getType();
    return type;
}

Actual code:

enter image description here

Debugger:

enter image description here

I we inspect the type2, we can see that it has the rawType of Arraylist and typeArgument of Integer . Same I want to happen with my generic type.

But in the varibale type we observe a rawType of Arraylist and typeArgument of T. Instead T I want the to be a concrete Class (Like Integer or MyCLass). Basically I need a generic List Type, but concrete at the point of execution. Is there a way to acomplish that?

-----Edit 1-----

It is not a duplicate of this question: Get generic type of class at runtime The answer there produces the same result as my code does.

Upvotes: 2

Views: 104

Answers (1)

Diego Veralli
Diego Veralli

Reputation: 1052

Due to type erasure, the T parameter isn't available at runtime inside getListClass, but you can use TypeToken.where (from Guava) to build the type using cls:

public <T> Type getListClass(Class<T> cls) {
    Type type = new TypeToken<ArrayList<T>>() {}.where(new TypeParameter<T>() {}, cls).getType();
    return type;
}

Upvotes: 2

Related Questions