论坛首页 入门技术论坛

为什么运行时取不到泛型T,难道你们觉得没必要吗

浏览 15114 次
该帖已经被评为新手帖
作者 正文
   发表时间:2012-01-31  
没办法获取 泛型的类型是编译期确定的 实质上是编译器的对你代码的优化 运行期无法动态获取
0 请登录后投票
   发表时间:2012-01-31  
java 泛型的支持只是在编译器层面上,没有运行时的支持。
0 请登录后投票
   发表时间:2012-02-01  
我支持试过,网上有间接的实现的方法的。。 具体就是你都定义临时类,然后就可以取到了。
0 请登录后投票
   发表时间:2012-02-01  
在编译期间T被搞成Object,类型丢失,所以是不能直接取到的.但有时可以变通地取到,比如: 

public class GenericType<T> {
    protected GenericType() {
        Type superclass = getClass().getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
       
        Class<T> messageType = parameterized.getActualTypeArguments()[0];
    }

一般人俺不告诉他
0 请登录后投票
   发表时间:2012-02-01  
vcok 写道
在编译期间T被搞成Object,类型丢失,所以是不能直接取到的.但有时可以变通地取到,比如: 

public class GenericType<T> {
    protected GenericType() {
        Type superclass = getClass().getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
       
        Class<T> messageType = parameterized.getActualTypeArguments()[0];
    }

一般人俺不告诉他



我曾经做过java反射的一些开发,像你这样的可以通过java的反射方式拿到它的泛型,方式就是楼上这位兄弟给出的~
public <T> Object executeQuery(MybatisCallBack<T> callback){ 
Class<MybatisCallBack> clazz=callback.getClass();
//下面就是用楼上方式取这个class的泛型了
Type superclass = clazz.getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        
        Class<T> messageType = parameterized.getActualTypeArguments()[0];

}
0 请登录后投票
   发表时间:2012-02-01  
取得到的,我上一个公司一个小项目就写过,不过是参考的别人的代码然后自己改改,现在已经不记得怎么写的.我们当时是弄了一个抽象DAO类,泛型是操作数据库的映射持久类.
0 请登录后投票
   发表时间:2012-02-01  
java的泛型实现只是一种伪泛型。。内部用强制类型转换实现的。。
0 请登录后投票
   发表时间:2012-02-01  
vcok 写道
在编译期间T被搞成Object,类型丢失,所以是不能直接取到的.但有时可以变通地取到,比如: 

public class GenericType<T> {
    protected GenericType() {
        Type superclass = getClass().getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
       
        Class<T> messageType = parameterized.getActualTypeArguments()[0];
    }

一般人俺不告诉他


new GenericType<String>();取不到
GenericTypeString extends GenericType<String> new GenericTypeString();才取得到
0 请登录后投票
   发表时间:2012-02-01  
正在吸收各位提的意见
0 请登录后投票
   发表时间:2012-02-01  
根据楼上几位复杂的api实现,最后抛出Missing type parameter异常信息,我还是细心研究一下
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics