I have a snippet code for instantiation of a generic type as following:
public class GenericMessageMapper<I ,X>
{
public X xFromI(I imf)
{
// do thing by imf argument
Class<X> clazz = (Class<X>)((ParameterizedType)
this.getClass()
.getGenericSuperclass())
.getActualTypeArguments()[1];
X x = clazz.newInstance();
}
}
Above code worked fine but MyEclipse show a warning on the code(a yellow under line on preparing clazz variable line) by this message :Type safety: Unchecked cast from Type to Class<X>
I temporary add following annotation in above of xFromI method:
@SuppressWarnings("unchecked")
What is reason of this warning and what is solution?
ftom2 is right – in usual situation you should perform instance check (
instanceof) before cast in case of this warning. But in your case this is impossible because generics in Java was implemented by erasure.Class<X>is not reified type so it is impossible to use it for instance check and only way to turn off the warning is to use@SuppressWarnings(value = "unchecked").To learn more about generics you can use this book.