Java泛型中的Type体系

今天看一个开源库源码的时候,发现里面针对泛型Type做了很多处理,我这块不怎么了解,故此研究一下。

关于java.lang.reflect.Type的分类先说明一下,Type作为一个接口,下面有4个继承它的子接口,分别是TypeVariableParameterizedTypeWildcardTypeGenericArrayType。这里我就不给专业名词了,之前我看很多文章,给的专业名词,到最后我也没能区分清楚,这里就直接上例子,通过例子来说明。

  • TypeVariable

    这个怎么说,看字面翻译的意思是类型变量,我个人理解呢,它其实相当于在方法声明当中的形参。也就是你声明时写的是啥,获取到的就是啥。

    public class GenericType {
         
    
        public static void main(String[] args) {
            ChildCls childCls = new ChildCls();
        }
    }
    
    class SuperCls<K, V> {
    
        public SuperCls() {
            TypeVariable<?>[] typeParameters = getClass().getSuperclass().getTypeParameters();// [K,V]
            for (TypeVariable<?> typeVariable : typeParameters) {
                p("getSuperclass().getTypeParameters()=" + typeVariable);// 这里分别输出K,V
                Type[] bounds = typeVariable.getBounds();
                for (Type type : bounds) {
                    p(type);// 分别输出class java.lang.Object
                }
            }
        }
        void p(Object obj) {
            System.out.println(obj.toString());
        }
    }
    
    class ChildCls extends SuperCls<SuperCls<? extends String, ? super String>, Integer> {}
  • ParameterizedType

    这个,字面意思,参数化的类型。个人理解相当于你调用方法(声明的泛型类),并传入一些参数(泛型类型)。还是上面的例子。

    class SuperCls<K, V> {
    
    public SuperCls() {
        Type genericSuperclass = getClass().getGenericSuperclass();
        p("getGenericSuperclass()=" + genericSupe
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值