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
?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With