1

I'm trying to instantiate a generic class called "T" extending "AbstractLauncher" and I didn't understand all topic I saw on google. Could you help me ? I've got several class called ConcretXLauncher and I would not have on my MainClass "ConcretXLauncher" but only generics who could be whatever extending AbstractLauncher...

public MainClass < T extends AbstractLauncher > {

    public MainClass(Config config){
      //T launcher = new T(config); doesnt work, I want to do new ConcretXLauncher(config)     

      T launcher = newInstance(????); 
      // code using "launcher" 
    }

    public static < T > T newInstance(Class clazz) {
        return clazz.newInstance() ;
    }

}

In other topics, I saw this function but I don't know how to call it ? What do I have to put for "clazz" argument ?

Paul Bellora
  • 51,514
  • 17
  • 127
  • 176
  • We don't even know which language you're talking about... – Jon Skeet Apr 30 '13 at 19:55
  • You can't instantiate a generic class like this. `new T` doesn't work. – Louis Wasserman Apr 30 '13 at 20:00
  • Creating an instance of a generic type isn't currently possible, but you can implement the factory pattern. More information is available here http://en.wikipedia.org/wiki/Factory_method_pattern, and even better here http://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java. – Atlas Wegman Apr 30 '13 at 20:09
  • @AtlasWegman, I don't understand what is "clazz" in the second link. How could I call the fonction (Which argument to put) ? – Redouane B. Apr 30 '13 at 20:18
  • Take a look at the answer with 40 votes, it makes much more sense – Atlas Wegman Apr 30 '13 at 20:56

2 Answers2

0

Here's an example of how to define your newInstance method and call it:

public class Test {
  public static <T> T newInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
    return clazz.newInstance();
  }

  static class A {

    @Override
    public String toString() {
      return "hello";
    }
  }

  public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    A a = newInstance(A.class);
    System.out.println(a);
  }
}
GriffeyDog
  • 7,882
  • 3
  • 20
  • 32
0

You could use the following

public class MainClass < T extends AbstractLauncher> {

    public MainClass(Config config, Class<T> clazz) throws Exception {


      T launcher = newInstance(clazz); 
      // code using "launcher" 
    }

    public static <T> T newInstance(Class<T> clazz) throws Exception {
        return clazz.newInstance() ;
    }

}

you could introduce a custom runtime exception rather than throwing Exception from the constructor

Dev Blanked
  • 7,429
  • 3
  • 24
  • 32