简体   繁体   English

如何使用Java反射读取泛型参数的类类型

[英]How to read class types of generics parameters using Java reflection

I have a class BaseClass<X, Y, Z> . 我有一个类BaseClass<X, Y, Z> And I implement the class as SuperCar implements BaseClass<Color, Engine, Foo> . 我实现了该类,因为SuperCar implements BaseClass<Color, Engine, Foo> So now i need to get those X,Y,Z values by using reflection on SuperCar class. 所以现在我需要通过在SuperCar类上使用反射来获取这些X,Y,Z值。 Is this possible ? 这可能吗 ?

You can inspect the type parameters for the superclass, having the Class of the SuperCar : 您可以检查具有SuperCarClass的超类的类型参数:

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 无需打印名称,您可以随便使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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