Java泛型的类型擦除
2016-07-18 20:39
435 查看
JAVA的泛型是一种语法糖,当我们在新建一个容器类的时候,代码是这么编写的
编译后的JAVA代码是等价于
当中String的信息是不会带入到list中的,
list的存放的东西都是Object类型,相当于容器类的个体在编译后类型被擦除了。
我们可以试着编译代码成jar包,然后用jd-gui打开
你编写的容器类,你会发现你的容器类反编译后的代码是不带任何类型的。
但是有时候在容器类使用时候,我们需要获取容器所装载的类的类型信息时候,我们可以这么获取
ArrayList<String> list = new ArrayList<String>();
编译后的JAVA代码是等价于
ArrayList list = new ArrayList();
当中String的信息是不会带入到list中的,
list的存放的东西都是Object类型,相当于容器类的个体在编译后类型被擦除了。
我们可以试着编译代码成jar包,然后用jd-gui打开
你编写的容器类,你会发现你的容器类反编译后的代码是不带任何类型的。
但是有时候在容器类使用时候,我们需要获取容器所装载的类的类型信息时候,我们可以这么获取
package com.yuan; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author chenrenyuan */ public class MainTest { /** * @param args */ public static void main(String[] args) throws Exception{ Method method = T.class.getMethod("func1", Collection.class); Type inType = method.getGenericReturnType(); Type outType = method.getGenericParameterTypes()[0]; Type fieldType = T.class.getField("set").getGenericType(); if(inType instanceof ParameterizedType){ System.out.println(((ParameterizedType) inType).getActualTypeArguments()[0]); } if(outType instanceof ParameterizedType){ System.out.println(((ParameterizedType) outType).getActualTypeArguments()[0]); } if(fieldType instanceof ParameterizedType){ System.out.println(((ParameterizedType) fieldType).getActualTypeArguments()[0]); } } public class T{ public Set<Long> set; public List<Integer> func1(Collection<String> collection){ List<Integer> list = new ArrayList<Integer>(); return list; } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树