java中泛型在靜態方法中的使用


 1 @SpringBootTest  2 class HighConcurrencyApplicationTests {  3 
 4  @Test  5     void contextLoads() {  6         System.out.println(test("aaaaa"));  //aaaaa 基本用法
 7         System.out.println(test1("aa").get(0).equals("aa"));    //true 用於內部包裝
 8         System.out.println(test1(new HashMap()).get(0).put("", ""));    //比上一句更能說明用處的例子
 9         System.out.println(test2(new HashSet(), Collection.class).size());  //0 用於強制轉換類型
10         System.out.println(test3("bbbbb")); //bbbbb 裝神弄鬼
11 
12         HashSet ss = test(new HashSet());    //省去了強制轉換類型
13  ss.size(); 14 
15         test(new HashSet()).size();        //可以看出與句柄無關,是靜態方法自動做出的判斷 16 
17         //在方法中自動進行強制類型轉換,語法很特別。 18         //(這個語句毫無疑問會報錯,只是subList這個ArrayList有,而HashSet沒有的方法能更明確的展示這個語法)
19         test2(new HashSet(), ArrayList.class).subList(1, 1); 20  } 21 
22 
23     public static<T> T test(T obj){ 24         return obj; 25  } 26 
27     public static<T> List<T> test1(T obj){ 28         List<T> list = new ArrayList(); 29  list.add(obj); 30         return list; 31  } 32 
33     public static<T> T test2(Object str, Class<T> obj){ 34         return (T)str; 35  } 36 
37     public static<T> T test2(Object obj){ 38         return (T)obj; 39  } 40 
41     public static<T, A, B, C, D> B test3(B obj){ 42         return obj; 43     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM