要检索泛型类型的类实例,可以使用Java的反射机制。通过反射,可以获取类的泛型类型,并实例化该泛型类型的对象。下面是一个示例代码:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericClass {
private Class type;
public GenericClass() {
// 获取泛型类型
Type genericSuperclass = getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
if (actualTypeArguments != null && actualTypeArguments.length > 0) {
type = (Class) actualTypeArguments[0];
}
}
}
public T createInstance() throws IllegalAccessException, InstantiationException {
// 实例化泛型类型的对象
return type.newInstance();
}
}
使用上述代码,可以通过以下方式检索泛型类型的类实例:
public class MyClass {
public static void main(String[] args) {
GenericClass generic = new GenericClass() {};
try {
String instance = generic.createInstance();
System.out.println(instance);
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
在上述示例中,GenericClass
是一个泛型类,通过反射获取泛型类型 T
,并使用 newInstance()
方法实例化泛型类型的对象。在 MyClass
中,通过实例化 GenericClass
,可以获得一个 String
类型的实例。