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 ?
2 Answers
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
Comments
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
ArrayList<Car>is compiled toArrayList<Object>- compiler doesn't compile if you try to put aHelicopterinArrayList<Car>, but the runtime only seesArrayList<Object>and would happily allow it.