泛型:编译期有用 运行期没用
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)
{
}