简体   繁体   中英

How to read class types of generics parameters using Java reflection

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM