泛型知識
1、泛型是給java編譯器使用的,在源文件經過編譯后,編譯器會將類型信息去掉,所以
testList<String> ls = new ArrayList<String>(); List<Boolean> ls1 = new ArrayList<Boolean>(); System.out.println(ls==ls1) ; //true;
2、可以繞過編譯器的類型信息檢查,而直接加入對象
testimport java.util.* ; import java.lang.* ; public class Fanx { public static void main (String args[]) { ArrayList<Integer> ls = new ArrayList<Integer>(); try{ ls.getClass().getMethod("add", Object.class).invoke(ls,"abc") ; }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(ls.get(0)); } }//out:abc
3、泛型通配符
testpublic static void printCollection(Collection<?> coll) { //可以傳Collection<String>,Collection<Integer>,Collection<Boolean>等等,但在此方法內不能使用諸如coll.add(“Strin”)這樣具有類型信息的方法 for(Object obj:coll){ System.out.println(obj); }//coll.add(“str”); 報錯 }
4、限定通配符上邊界,限定通配符上邊界
testpublic static void printCollection1(Collection<? extends Number> coll) { // for(Object obj:coll){ System.out.println(obj); } } //printCollection1(new ArrayList<Integer>()) ;//不報錯 //printCollection1(new ArrayList<String>()) ; //報錯,傳入泛型參數必須為Number的子類
testpublic static void printCollection2(Collection<? super Number> coll) { // for(Object obj:coll){ System.out.println(obj); } } //printCollection1(new ArrayList<Integer>()) ;//不報錯 //printCollection1(new ArrayList<String>()) ; //報錯,傳的參數化必須是以Number為父類
5、自定義泛型方法
testpublic <T> T swap(T[] t,int i,int j){ T temp = t[i] ; t[i] = t[j] ; t[j] = t[i] ; return (T) t ; }
6、類級別泛型
testpublic class Dao<T> { public <T> T getEntity(int id){ return null; } }
7、通過反射獲得泛型的實際類型參數
testimport java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Date; import java.util.Map; import java.util.Vector; //假如我們要想獲得 Vector<Date> v = new Vector<Date>(); v的實際類型參數 //我們必須寫一個如applyRef的方法 public class Dao { public void applyRef1(Map<String,Integer> map,Vector<Date> v){ } public static void main(String[] args) { try { Method method = new Dao().getClass().getMethod("applyRef1", Map.class,Vector.class) ; Type[] pType = method.getParameterTypes(); Type[] neiType = method.getGenericParameterTypes(); System.out.println(pType[0]) ; System.out.println(pType[1]) ; System.out.println(neiType[0]) ; System.out.println(neiType[1]) ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
posted on 2011-03-05 19:45 jack zhai 閱讀(94) 評論(0) 編輯 收藏 所屬分類: java2 se