0

I have a class BaseClass<X, Y, Z>. And I implement the class as SuperCar implements BaseClass<Color, Engine, Foo>. So now i need to get those X,Y,Z values by using reflection on SuperCar class. Is this possible ?

marek.jancuska
  • 310
  • 1
  • 7
dinesh707
  • 12,106
  • 22
  • 84
  • 134
  • I guess it is not possible, remember that Java generics use erasure, the type parameters are "forgotten" after compilation. E.g. `ArrayList` is compiled to `ArrayList` - compiler doesn't compile if you try to put a `Helicopter` in `ArrayList`, but the runtime only sees `ArrayList` and would happily allow it. – marek.jancuska Mar 19 '15 at 14:46
  • 1
    There is a excellent answer on this post to explain how to do this. http://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection – APD Mar 19 '15 at 14:52

2 Answers2

1

You can inspect the type parameters for the superclass, having the Class of the SuperCar:

SuperCar car = new SuperCar();
ParameterizedType parameterizedType = (ParameterizedType) car.getClass().getGenericSuperclass();
Type[] superClassTypes = parameterizedType.getActualTypeArguments();
for (Type type : superClassTypes) {
    System.out.println(type.getTypeName());
}

This should give you:

Color
Engine
Foo
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

i guess you want to have something like this:

ParameterizedType types = (ParameterizedType) SuperCar.class.getGenericInterfaces()[0];
for (Type type : types.getActualTypeArguments()) {
    Class<?> cl = (Class<?>) type;
    System.out.println(cl.getName());
}

instead of printing the name you can do whatever you like with it

Pinguin895
  • 999
  • 2
  • 11
  • 28