泛型:自定义泛型方法

1、自定义泛型方法的格式



 

2、自定义泛型方法的代码

package com.atguigu.generic;

/**
 * 自定义泛型方法
 * @author LiPiaoShui
 */
public class User<T> {

	/**
	 * 此自定义泛型方法使用了自定义泛型类中的泛型,不需要添加<T> 
	 */
	public T getT(T t) {
		return t;
	}
	
	/**
	 * 此自定义泛型方法没有使用泛型类中的泛型,需要添加<E> 
	 */
	public <E> E getE(E e) {
		return e;
	}
	
	/**
	 * 静态方法中可以使用非类的其他泛型
	 */
	public static <E> void show(E e) {
		System.out.println(e);
	}
	
//	/**
//	 * 以下方法会报编译错误,因为静态方法中不能使用类的泛型
//	 */
//	public static void show(T t) {
//		System.out.println(t);
//	}
	
//	/**
//	 * 不能在catch中使用泛型
//	 */
//	public void tryFun() {
//		try {} catch(T t) {}
//	}
	
}

3、测试自定义泛型方法的代码

//4.自定义泛型方法
@Test
public void test4() {
	User<Boolean> user = new User<Boolean>();
	Boolean flag = user.getT(true);
	//输出:true
	System.out.println(flag);
	int score = user.getE(90);
	//输出:90
	System.out.println(score);
}

4、静态方法中不能使用类的泛型



 

5、静态方法中可以使用其他的非类泛型



 

6、不能在catch中使用泛型



 

猜你喜欢

转载自lipiaoshui2015.iteye.com/blog/2264436