来自类型变量的Java类对象 [英] Java class object from type variable
本文介绍了来自类型变量的Java类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法从Java泛型类中的类型变量中获取Class对象?类似的东西:
public class Bar extends Foo< T> {
public Class getParameterClass(){
return T.class; //没有编译
}
}
此类型信息可用在编译时,因此不应该受到类型擦除的影响,所以理论上应该有一种方法来实现这一点。它是否存在?
解决方案
public static class Bar extends Foo< String> {
public Class<?> getParameterClass(){
return(Class<>)(((ParameterizedType)Bar.class.getGenericSuperclass())。getActualTypeArguments()[0]);
}
}
Is there a way to get Class object from the type variable in Java generic class? Something like that:
public class Bar extends Foo<T> {
public Class getParameterClass() {
return T.class; // doesn't compile
}
}
This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?
解决方案
This works:
public static class Bar extends Foo<String> {
public Class<?> getParameterClass() {
return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
这篇关于来自类型变量的Java类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文