-1

I am wondering if the Java gods out on SO have any tricks to share on how to make the following work

public class MyClass<T> {

   public List<T> getMyList(Class1 a, String, b) {
        Generic1<Generic2<T>, Class1> x = new Generic3<T>();
        x.doSomething();
        // this compiles but x doesn't work correctly since (of course) T is now type "Object"
   }
}

//... calling it like this:
MyClass<MyType> c = new MyClass<>();

For object "x" above to do its job, it needs to know what the type for T is. Generic1, Generic2 and Generic3 are not classes that I wrote. But is there any way to convey the type information so they would work? Say, if I pass in the Class of the type at runtime?

Thanks.

azurefrog
  • 10,785
  • 7
  • 42
  • 56
pastafarian
  • 1,010
  • 3
  • 16
  • 30

1 Answers1

-1

Pass in a Class<T> object and use .newInstance() instead of new.

public class MyClass<T> {
    private final Class<T> clazz;

    public MyClass(final Class<T> clazz)
        { this.clazz = clazz; }

    public List<T> getMyList(Class1 a, String, b) {
        Generic1<Generic2<T>, Class1> x = this.clazz.newInstance();
        x.doSomething();
    }
}

//... calling it like this:
MyClass<MyType> c = new MyClass<>(MyType.class);
dsh
  • 12,037
  • 3
  • 33
  • 51
  • Thanks. I see a bit of difference between your code and my use case. I am not actually creating an instance of Class ... but I am creating a new instance of Generic3() – pastafarian Aug 28 '15 at 21:25
  • nice solution, but it wont always work, ie if there is no noargs constructor in main class it will crash. but you can do it better, by creating interface provider, with single method create object. and pass implementation of this interface to your class via constructor. first it is more oop solution, second it will allow to choose best constructor – user902383 Aug 28 '15 at 21:27