2

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.

SG Tech Edge
  • 477
  • 4
  • 16
  • Does this answer your question? [Get generic type of class at runtime](https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime) – Milgo Oct 21 '20 at 06:08
  • @Milgo I does not. The answer there produces the same result as my method. – SG Tech Edge Oct 21 '20 at 07:01

1 Answers1

2

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;
}
Diego Veralli
  • 1,011
  • 6
  • 13