[英]How to get concrete type of a generic interface
I have an interface 我有一个界面
public interface FooBar<T> { }
I have a class that implements it 我有一个实现它的类
public class BarFoo implements FooBar<Person> { }
With reflection, I want to take an instance of BarFoo and get that the version of FooBar it implements is Person. 通过反射,我想获取BarFoo的一个实例并得到它实现的FooBar版本是Person。
I use .getInterfaces
from BarFoo to get back to FooBar, but that doesn't help me find out what T is. 我使用.getInterfaces
的.getInterfaces来回到FooBar,但这并不能帮助我找出T是什么。
You can grab generic interfaces of a class by Class#getGenericInterfaces()
which you then in turn check if it's a ParameterizedType
and then grab the actual type arguments accordingly. 您可以通过Class#getGenericInterfaces()
获取类的泛型接口,然后依次检查它是否为ParameterizedType
,然后相应地获取实际的类型参数 。
Type[] genericInterfaces = BarFoo.class.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
if (genericInterface instanceof ParameterizedType) {
Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
for (Type genericType : genericTypes) {
System.out.println("Generic type: " + genericType);
}
}
}
Try something like the following: 尝试以下内容:
Class<T> thisClass = null;
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] typeArguments = parameterizedType.getActualTypeArguments();
thisClass = (Class<T>) typeArguments[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.