泛型


泛型:编译期有用  运行期没用

ArrayList<Integer> arr = new ArrayList<Integer>();
arr.getClass().getMethod("add", Object.class).invoke(arr, "abc");
System.out.println(arr.get(0));


//这句话是错误的,泛型不考虑父子的关系(没有继承的关系)
//Collection<Object> o = new Collection<Integer>();

<span style="white-space:pre">	</span>Collection<Integer> col = new ArrayList<Integer>();
	col.add(1);
	printCollection(col); //这里是不能直接调用的
        public static void printCollection(Collection<Object> collection)
	{
		
	}
1、?通配符(任意类型)

<span style="white-space:pre">	</span>Collection<Integer> col = new ArrayList<Integer>();
	col.add(1);
	printCollection(col);
	public static void printCollection(Collection<?> collection)
	{
		
	}

Collection<Object> c = new ArrayList<Integer>();//错误
Collection<?>  c = new ArrayList<Integer>();//正确
2、?通配符的扩展
限定通配符的上边界
Vector<? extends Number> v = new Vector<Integer>();//正确  Number及继承Number的类
Vector<? extends Number> v2 = new Vector<String>();//错误
限定通配符的下边界
Vector<? super Integer> v3 = new Vector<Number>();//正确  Integer及Integer的父类
Vector<? super Integer> v4 = new Vector<byte>();//错误
        add(2, 3)
	public static <T> T add(T a,T b)
	{
		return b;
		
	}


其中的<T>的作用是声明类型T,也可以声明类型的范围,<T extends Integer>,也可以声明多个类型<K extends Integer,V extends String>

当为了确保一个类中的所有泛型统一,则在类上面声明泛型。

public class  GeneralDao<T> {
	public void add(T t)
	{
	}
	
	public T findById(int id)
	{
		
		return null;
	}
}

通过反射获取类上面的泛型

        public static void main(String[] args) throws Exception {
		Vector<Date> v1 = new Vector<Date>();//获取vector中的具体泛型,直接是获取不到的,需要传入函数中,通过方法获取
		
		Method method = GeneralDao.class.getMethod("getGenral", Vector.class);
		Type[] types = method.getGenericParameterTypes();
		ParameterizedType pt = (ParameterizedType)types[0];
		System.out.println(pt.getRawType());
		System.out.println(pt.getActualTypeArguments()[0]);
	}
	
	public static void getGenral(Vector<Date> v)
	{
		
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值