泛型:泛型類和泛型方法
阿新 • • 發佈:2019-03-16
throws exceptio sys fun hello one type trac tac
一、泛型類
1.1、定義泛型類
public class A<T> { // 泛型類 private T a; public T getA() { return a; } public void setA(T a) { this.a = a; } }
1.2、繼承泛型類的幾種方式
class B1 extends A<String> {} class B2<E> extends A<String> {} classB3<E> extends A<E> {} class B4<E1, E2> extends A<E1> {}
二、泛型方法
例子1:
package com.oy.type; public class Demo01 { public static void main(String[] args) { fun(2); fun(20.0); fun("hello"); } public static <T> void fun(T a) { //泛型方法,<T>定義在返回值前面 System.out.println(a); } }
例子2:
public class Demo02 { public static void main(String[] args) { String str = null; try { str = fun2(String.class); } catch (Exception e) { e.printStackTrace(); } System.out.println("str = " + str); // str = Integer i = null; try { // Integer類沒有空參構造,調用Class類的newInstance()方法時拋InstantiationException異常 i = fun2(Integer.class); } catch (Exception e) { e.printStackTrace(); } System.out.println("i = " + i); // i = null } public static <T> T fun2(Class<T> clazz) throws Exception { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); throw new Exception("創建對象出錯!"); } } }
泛型:泛型類和泛型方法