1. 程式人生 > >java泛型關於方法返回值前面的<T>是什麼?

java泛型關於方法返回值前面的<T>是什麼?

public <T> Test<String,T> setCacheObject(String key,T value){
    return null;
}
  • 前面的T的宣告,跟類後面的 <T> 沒有關係。
  • 方法前面的<T>是給這個方法級別指定泛型。

請看示例:

package com.fanx;

public class Fruit {

	public String toString() {
		return "fruit";
	}
}

 

package com.fanx;

public class Apple extends Fruit{

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "apple";
	}

	
}
package com.fanx;

public class Dog {

	public String toString() {
		return "dog";
	}
}

 

package com.fanx;

public class ClassName<T> {

	void show_1(T t) {
        System.out.println("show_1  " + t.toString());
    }

    <E> void show_2(E e) {
        System.out.println("show_2  " + e.toString());
    }

    <T> void show_3(T t) {
        System.out.println("show_3  " + t.toString());
    }
    public static void main(String[] args) {
    	ClassName<Fruit> o = new ClassName<Fruit>();//建立一個ClassName例項,限定它的型別為Fruit
        Fruit f = new Fruit();
        Apple a = new Apple();
        Dog dog = new Dog();
        System.out.println("-----------------演示一下show_1------------------");
        o.show_1(f);
        o.show_1(a);
        //o.show_1(dog);這是不能編譯通過的,因為此時o物件已限定為Fruit類
        System.out.println("-----------------演示一下show_2-----------------");
        o.show_2(f);
        o.show_2(a);
        o.<Dog>show_2(dog);
        System.out.println("-----------------演示show_3-------------------");
        o.show_3(f);
        o.show_3(a);
        o.<Dog>show_3(dog);
	}
}
  • 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產生衝突。