您的位置:首页 > 编程语言 > Java开发

Java泛型的类型擦除

2016-07-18 20:39 435 查看
JAVA的泛型是一种语法糖,当我们在新建一个容器类的时候,代码是这么编写的

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