您的位置:首页 > 其它

泛型:自定义泛型方法

2015-12-16 10:21 211 查看

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中使用泛型



 

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: