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