一、泛型类
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> {} class B3<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("创建对象出错!"); } } }