0

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?

Sam
  • 6,106
  • 6
  • 42
  • 78

3 Answers3

2

A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.

In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this just before the line:

@SuppressWarnings (value="unchecked")

refer Type safety: Unchecked cast

Community
  • 1
  • 1
Hemant Metalia
  • 25,838
  • 17
  • 67
  • 86
1

It only means that the type of the class is only known at runtime, so a situation could arise where you think you are supposed to get a class of type X but actually it is of other type (it doesn't know it in compile time since X can be of any type).

Basically you can ignore this warning.

Tomer
  • 16,381
  • 13
  • 64
  • 124
1

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.

Community
  • 1
  • 1
gkuzmin
  • 2,174
  • 15
  • 24