Powered by Blogger.

Java Generics Parameterized Types and Raw Types

To create parameterized type of GenericClazz 
  • GenericClazz integerClazz = new GenericClass<>();
To create raw type of GenericClazz, the type argument has to be removed
  • GenericClazz rawClazz = new GenericClazz();
Therefore GenericClazz is the raw type of the generic type GenericClazz. However, a non-generic class or interface type is not a raw type.

Raw Types:

The Raw Types bypass generic type checks, and put off the unsafe code to runtime. Therefore, you should avoid using raw types. You can see Raw types in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0.

When you use raw types now in your code, you can see pre-generics behaviour as explained below:

  • For backward compatibility, assigning a parmaterized type to its raw type is allowed.
          GenericClazz integerGClazz1 = new GenericClazz();
          GenericClazz rawClazz1 = integerGClazz1; //OK
  • You will get type safety warning if you assign a raw type to a parameterized type.
          GenericClazz rawClazz2 = new GenericClazz();
          GenericClazz integerGClazz2 = rawClazz2; //Type safety warning: Unchecked conversion.
  • You also will get type safety warning if you use raw type to invoke generic methods.
          GenericClazz stringGClazz = new GenericClazz();
          GenericClazz rawClazz3 = stringGClazz;
          rawClazz3.setT(8); //Type Safety Warning: Unchecked invocation to setT(T)

RawTypeTest.java:

GenericClazz.java:

Refer Type Erasure for more information on how java compiler uses raw types.

0 comments:

Post a Comment