4 Replies Latest reply: Mar 18, 2010 7:07 AM by jtahlborn RSS

    How to instantiate generic parameter type

    843793
      Hi,

      I want to instantiate generic parameter type.

      Below is the sample code for better understanding, although they might be trivial.
      public class GenericParamBaseType {
           @Override
           public String toString() {
                return "GenericParamBaseType";
           }
      
      }
      public class GenericParamSubTypeA extends GenericParamBaseType {
      
           @Override
           public String toString() {
                return "GenericParamSubType A";
           }
      
           
      }
      public class GenericParamSubTypeB extends GenericParamBaseType {
      
           @Override
           public String toString() {
                return "GenericParamSubType B";
           }
      
      
      }
      import java.util.ArrayList;
      import java.util.List;
      
      public class ParameterizedClass<E extends GenericParamBaseType> {
      
           public void populateList(List<E> subtypeList) throws Exception {
                // find out type of E, reflection?! or any simple way?
                //create instance of E
           }
      
           public static void main(String[] args) throws Exception {
                ParameterizedClass<GenericParamSubTypeA> pa = new ParameterizedClass<GenericParamSubTypeA>();
                pa.populateList(new ArrayList<GenericParamSubTypeA>());
           }
      
      }
      Cheers