要定义泛型方法,只需将泛型参数列表置于返回值之前

package tuple;
/**
 * 泛型方法
 * 当使用泛型类时,必须在创建对象实例的时候指定类型参数的值
 * 而使用泛型方法的时候,通常不必指明参数类型,编译器会为我们找出具体的类型--->	类型参数推断  type argument inference
 * @author Youjie
 *
 */
public class Foo {
	/**
	 * 方法push 像被无限重载过一样,可以接受任何参数...
	 * @param target
	 */
	public <T> void push(T target){
		System.out.println(target);
	}
	
	public static void main(String[] args) {
		Foo foo = new Foo();
		
		foo.push(1);
		foo.push("字符串");
		foo.push(new Foo());
		foo.push(1.0F);
		foo.push(2L);
		foo.push(new Thread());
	}
}

注意:如果是静态的方法,必须要声明为泛型方法。因为他并不是在类实例化时才调用。

相关文章:

  • 2021-09-11
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
  • 2021-05-05
猜你喜欢
  • 2021-11-29
  • 2022-02-09
  • 2021-08-04
相关资源
相似解决方案