public class GenericType {
public static void main(String[] args) {
/**
* 泛型:用泛型,编译器会提醒你应该在集合中添加什么类型(只是提醒)
* 当然,你可以用反射技术添加任意类型的数据
* 所以这只是在源文件提醒(SOURSE),而不会在内存中体现(RUNTIME),所以结果是true
*/
Collection<String> strLists = new ArrayList<String>();
Collection<Integer> intLists = new ArrayList<Integer>();
System.out.println(strLists.getClass() == intLists.getClass());//true
//intLists.add("abc"); //编译器会报错
//利用反射技术添加一个字符串类型的变量
try {
Method intMethod = intLists.getClass().getMethod("add", Object.class);
intMethod.invoke(intLists, "abc");
} catch (Exception e) {
e.printStackTrace();
}
//直接打印出来,不类型转换,还没有get方法,打印结果abc
System.out.println(((ArrayList<Integer>) intLists).get(0));
/**Map类型**/
Map<String, Integer> mymap = new HashMap<String, Integer>();
/**
* 对于HashMap,它有key,value,Entry类型,包含了Key,Value
*/
mymap.put("111", 222);
Set<Entry<String,Integer>> entrySet = mymap.entrySet();
for(Entry<String,Integer> entry :entrySet){
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
反射==>突破编译器的泛型检验
最新推荐文章于 2025-01-12 21:15:19 发布