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 ?

2
  • I guess it is not possible, remember that Java generics use erasure, the type parameters are "forgotten" after compilation. E.g. ArrayList<Car> is compiled to ArrayList<Object> - compiler doesn't compile if you try to put a Helicopter in ArrayList<Car>, but the runtime only sees ArrayList<Object> and would happily allow it. Commented Mar 19, 2015 at 14:46
  • 1
    There is a excellent answer on this post to explain how to do this. stackoverflow.com/questions/1901164/… Commented Mar 19, 2015 at 14:52

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.