3 Replies Latest reply: Aug 6, 2011 10:50 PM by DarrylBurke RSS

    Instantiation of generic type

    880739
      Hi.

      I have an issue with instantiating of generic type. My issue is similar to this Re: creating instance of generic type post.

      So I have the following class

      public class VehicleForm<V extends Vehicle>{
      private V vehicle;
      private Double price;
      private Class<V>vItemClass;

      public V getVehicle(){
      return this.vehicle;
      }

      public void setVehicle(V vehicle){
      this.vehicle=vehicle;
      }

      public Double getPrice(){
      return this.price;
      }

      public void setPrice(Double price){
      this.price=price;
      }

      private final Class<V> getGenericClassInstance() {
      Class<V> persistentClass = null;
      Type genericType = getClass().getGenericSuperclass();

      if (genericType instanceof ParameterizedType) {
      ParameterizedType pType = ((ParameterizedType) genericType);
      // obtaining first generic type class
      persistentClass = (Class<V>) pType.getActualTypeArguments()[0];
      }

      return persistentClass;
      }

      public VehicleForm(){
      this.vItemClass=getGenericClassInstance();//vItemClass is null
      this.vehicle=this.vItemClass.newInstance();//null poiner exception
      }
      }

      I cannot write in default constructor

      public VehicleForm(){
      this.vehicle=new V();//runtime error will occure
      }

      because of generic type

      For obtaining generics we can use java reflection functionality. Generic type list in runtime is obtaining through ParameterizedType. The code in getGenericClassInstance is standard to instantiate generic type var.

      But unfortunately in my case it doesn't work. getGenericClassInstance returns null. Line Type genericType = getClass().getGenericSuperclass(); doesnt get generic type which is instance of ParameterizedType, so the condition if (genericType instanceof ParameterizedType) is false. My genericType is Object instance, but not ParameterizedType. So I cannot create Class<V> instance from null.

      Can anybody help me? Thanks in advance.

      Edited by: 877736 on 06.08.2011 12:50

      Edited by: 877736 on 06.08.2011 12:51