黑马程序员-通过反射获取泛型参数类型

----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

package com.itcast.test2;
import java.util.*;
import java.lang.reflect.*;
public class GenericTest {
	/**
	 * HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
	 * 这个里面我们是无法通过变量hashMap而得到HashMap中参数的类型,
	 * 因为HashMap<String,Integer>在编译后字节码中去掉了类型
	 * 也就是说HashMap<String,Integer>和和HashMap<K,V>的字节码是一样的,
	 * 所以不能取得HashMap<String,Integer>中的参数类型,那我们可以通过把hashMap作为
	 * 一个参数传入一个方法中来获得HashMap<String,Integer>中的参数类型,
	 * 因为通过反射获得的Method中有能够获得参数化的类型的方法
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Method useParameterMethod = Class.forName("com.itcast.test2.GenericTest").getMethod("useParameter",HashMap.class);
		Type[] gType = useParameterMethod.getGenericParameterTypes(); // 取得属性的泛型类型
		ParameterizedType pType = (ParameterizedType)gType[0];
		System.out.println(pType.getRawType()); // 获取原始类型
		Type[] tArgs = pType.getActualTypeArguments(); // 获取参数类型
		for(Type t : tArgs) {
			System.out.println(t);
		}
		}
	// 此方法作用就是在主方法中通过反射调用该方法获取参数类型
	public static void useParameter(HashMap<String,Integer> hashMap) {}
}

----------- android培训java培训、java学习型技术博客、期待与您交流! ------------


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值