Dieses Blog durchsuchen

Mittwoch, 17. März 2010

Instantiate a Generic Type in Java

Once you used generics for a while you might stumble upon the following question:

public class MySample {
       private     T    mySample = null;


       public MySample() {
               mySample = new T();  // well this would be fine, but it doesn't work because the compiler doesn't know the type at this time!
      }
}

Ok, fair enough the compiler doesn't know if T is an interface or an object and couldn't instantiate the type. If your T is a class you could solve the question with this:



public class MySample {
       private     T    mySample = null;

       public MySample(Class _class) {
               mySample = _class.newInstance();
      }
}


This should work with the little overhead of specifying the class in the generic and the constructor:



  MySample  sample = new MySample(Whatever.class);