java 匿名内部类存储泛型参数,即类型参数

这个问题我是从反序列化String到泛型类开始得。很明显我们需要把泛型类型传递进去。这里一般用到的是typereference。

注意一个细节一定要使用匿名内部类,即下面这样声明。

TypeReference<HuaziResult<Human>> type = new TypeReference<HuaziResult<Human>>() {
};

这让我感觉很不舒服,为什么不是传递一个Class类型进去或者是有没有什么其它得方法获取到,再看看TypeReference的源码

public abstract class TypeReference<T> implements Comparable<TypeReference<T>>
{
    protected final Type _type;
    
    protected TypeReference()
    {
        Type superClass = getClass().getGenericSuperclass();
        if (superClass instanceof Class<?>) { // sanity check, should never happen
            throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
        }
       
        _type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    }

    public Type getType() { return _type; }
    
    /**
     * The only reason we define this method (and require implementation
     * of <code>Comparable</code>) is to prevent constructing a
     * reference without type information.
     */
    @Override
    public int compareTo(TypeReference<T> o) { return 0; }
    // just need an implementation, not a good one... hence ^^^
}

这里面维护的_type就是类型信息了,在试过了非匿名内部类的一些其他方法后。获取的都是被擦除的信息就是传进去的标志符号类似于(E,T)这种。

 

但是使用匿名内部类。是可以获取到的。

 其实从类加载角度我们可能可以知道为什么会这样。类只会被加载一次。Class对象只会被类加载器初始化。也就是说不可能根据运行时信息去修改。这就是为什么除了匿名内部类其它得泛型都获取不到信息。你想要获取到动态的类型信息,那就使用匿名内部类这种在运行时创建的类去保存参数化类型信息。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值