反射==>突破编译器的泛型检验

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());
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值