java方法返回值前面的泛型是什么?

1 public <T> Test<String,T> setCacheObject(String key,T value){
2     return null;
3 }
  • 前面的T的声明,跟类后面的 <T> 没有关系。
  • 方法前面的<T>是给这个方法级别指定泛型

直接上例子了

 1 package com.system.net.generic;
 2 
 3 class Fruit {
 4     public String toString() {
 5         return "Fruit";
 6     }
 7 }
 8 
 9 class Apple extends Fruit {
10     public String toString() {
11         return "Apple";
12     }
13 }
14 
15 class Person {
16     public String toString() {
17         return "Person";
18     }
19 }
20 
21 class ClassName<T> {
22     void show_1(T t) {
23         System.out.println("show_1  " + t.toString());
24     }
25 
26     <E> void show_2(E e) {
27         System.out.println("show_2  " + e.toString());
28     }
29 
30     <T> void show_3(T t) {
31         System.out.println("show_3  " + t.toString());
32     }
33 
34     public static void main(String[] args) {
35         ClassName<Fruit> o = new ClassName<Fruit>();
36         Fruit f = new Fruit();
37         Apple a = new Apple();
38         Person p = new Person();
39         System.out.println("show_1 演示________________________");
40         o.show_1(f);
41         o.show_1(a);
42 //        o.show_1( p );  是不能编译通过的。因为在 ClassName<Fruit>中已经限定了全局的T为Fruit,所以不能再加入Person;
43         System.out.println("show_2 演示________________________");
44         o.show_2(f);
45         o.show_2(a);
46         o.<Person>show_2(p);
47         System.out.println("show_3 演示________________________");
48         o.show_3(f);
49         o.show_3(a);
50         o.show_3(p);
51     }
52 }
  • show_2 和 show_3 方法其实是完完全全等效的。意思就是说ClassName中一旦T被指定为Fruit后,那么 show_1 没有前缀<T>的话,该方法中只能是show_1 (Fruit对象)

  • 而你要是有前缀<T><E>的话,那么你就是告诉编译器对它说:这是我新指定的一个类型,跟ClassName<T>类对象中的T没有半毛钱的关系。也就是说这个show_3中的T和show_2中的E是一个效果,也就是你可以把show_3同等程度地理解为<E> void show_3(E e){~~~~~}

从上面我说的看,那就是 这个方法返回值前也加个的话,这个T就代表该方法自己独有的某个类,而不去和类中限定的T产生冲突,你直接换成会更容易理解的。如例子中的:

1 o.<Person>show_2(p);
原文地址:https://www.cnblogs.com/zhncnblogs/p/13608913.html