yassiro
yassiro

Reputation: 23

Name of Class <T> of a generic Class

I have a small problem in java while using generics. I have a class A :

public class A<T>

In a method of A, I need to get the type name of T. Is there a way to find the string s using T ?

(If I create A<String> temp = new A<String>();, I want to be able to get java.lang.String at one point - I have to use generics because one of my methods will have to return a List).

This seems quite easy but I do not see how to do it.

Thanks a lot in advance for your help.

Upvotes: 2

Views: 217

Answers (2)

ruakh
ruakh

Reputation: 183381

This is not possible, because generics are implemented using "erasure": there's actually just a single A class internally, and the <String> gets "erased" before run-time. The best solution, in my experience, is to add a private final field, Class<T> tClass, and to require it to be specified in the constructor:

public A(final Class<T> tClass)
{
    this.tClass = tClass;
}

You would then have to write

A<String> temp = new A<String>(String.class);

instead of just

A<String> temp = new A<String>();

Upvotes: 2

SLaks
SLaks

Reputation: 887547

Due to type erasure, this is not possible.

Instead, you need to accept a Type<T> in your constructor.

Upvotes: 3

Related Questions