Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Class<?> object of a generic type

Tags:

java

generics

I have a static method which will return a custom type based on the type of the class,

public class GenericMethod {

    public static <T> T returnGeneric(Class<T> clazz) {
        return null;
    }

}

Now, I want to pass a class with a generic type in to it,

CustomType<String> type = GenericMethod.returnGeneric(CustomType.class);

Only problem is that the above statement gives and unchecked conversion warning.

I tried the workaround new CustomType<String>().getName() which is also not solving the problem.

Is there a right way to it, or the only solution is to use @SuppressWarnings ?

like image 614
anoopelias Avatar asked Nov 01 '22 11:11

anoopelias


1 Answers

What you would/should like to try is this:

CustomType<String> type = GenericMethod.returnGeneric(CustomType<String>.class);

Unfortunately, because of type erasure there is no difference between CustomType<A>.class and CustomType<B>.class, hence this syntax is not supported by Java.

So my $.02: what you are asking for is not possible, so hang on to the @suppresswarnings...

like image 75
GerritCap Avatar answered Nov 04 '22 11:11

GerritCap