1
public class superA<TypeX> {
    public superA(){
        TypeX var1 = new .......
    }
}

Imagine the above code, how do I find the type of TypeX if I wish to create a variable of that type before I receive any other information in the constructor?

Lordbalmon
  • 1,634
  • 1
  • 14
  • 31
  • 7
    You can't use it like that. At runtime generic types are [erased](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html). You will have to pass some Class or actual object of TypeX to get information about its class and then (with little help of reflection) create new instance. – Pshemo Mar 12 '14 at 01:20
  • Just to complement @Pshemo 's comment, write your method like this: `public superA(Class clazz)` and then use this `clazz` object and reflection to create your new object – morgano Mar 12 '14 at 01:24
  • @Pshemo - You should post this as an answer. – Ted Hopp Mar 12 '14 at 02:10
  • @Pshemo, I've come to the same conclusion, I was hoping for something like in C#, where you can extract the class object just to verify, like for example "TypeX.class == String.class" – Lordbalmon Mar 12 '14 at 03:13
  • @morgano, but even then it has to be passed explicitly, as I mentioned in my previous comment I am trying to make the code understand the class by comparing a few predefined types. – Lordbalmon Mar 12 '14 at 03:14

0 Answers0