添加
ArrayList<String> a = new ArrayList<String>();
a.add("CSDN_SEU_Cavin");
Class c = a.getClass();
try{
Method method = c.getMethod("add",Object.class);
method.invoke(a,100);
System.out.println("lgqname:" +a);
}catch(Exception e){
e.printStackTrace();
}
结果
lgqname:[CSDN_SEU_Cavin, 100]
或者
List list = new ArrayList();
list.add("CSDN_SEU_Cavin");
list.add(100);
泛型类、
public class Generic<T>{
//key这个成员变量的类型为T,T的类型由外部指定
private T key;
public Generic(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
this.key = key;
}
public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
return key;
}
}
传入的实参
//泛型的类型参数只能是类类型(包括自定义类),不能是简单类型
//传入的实参类型需与泛型的类型参数类型相同,即为Integer.
Generic<Integer> genericInteger = new Generic<Integer>(123456);
//传入的实参类型需与泛型的类型参数类型相同,即为String.
Generic<String> genericString = new Generic<String>("key_vlaue");
获取实参
Log.d("泛型测试","key is " + genericInteger.getKey());
Log.d("泛型测试","key is " + genericString.getKey());
泛型通配符
public void showKeyValue1(Generic<?> obj){
Log.d("泛型测试","key value is " + obj.getKey());
}
应用1
private void navigate(Class<?> destination) { Intent intent = new Intent(BaseActivity.this, destination); startActivity(intent); }