1.概念
泛型是Java 1.5版本才引进的概念,在这之前是没有泛型的,但是泛型代码能够很好地和之前版本的代码兼容。那是因为,泛型信息只存在于代码编译阶段,在进入JVM之前,与泛型相关的信息会被擦除掉,我们称之为–类型擦除。
2.分类:
- 无限制类型擦除
代码演示:
1 package com.genericity.demo5; 2 3 public class Earase<T> { 4 private T key; 5 6 public T getKey() { 7 return key; 8 } 9 10 public void setKey(T key) { 11 this.key = key; 12 } 13 }
1 package com.genericity.demo5; 2 3 import org.omg.PortableInterceptor.INACTIVE; 4 5 import java.lang.reflect.Field; 6 import java.util.ArrayList; 7 8 public class Test2 { 9 public static void main(String[] args) { 10 Earase<Integer> integerEarase=new Earase<>(); 11 //利用反射,获取Earase类的字节码文件的class类对象 12 Class<? extends Earase> aClass = integerEarase.getClass(); 13 Field[] declaredFields = aClass.getDeclaredFields(); 14 for (Field declaredField : declaredFields) { 15 System.out.println(declaredField.getName()+":"+declaredField.getType().getSimpleName()); 16 } 17 } 18 } 19 //运行结果:key:Object
- 有限制类型擦除
1 package com.genericity.demo6; 2 3 public class Earase<T extends Number> { 4 private T key; 5 6 public T getKey() { 7 return key; 8 } 9 10 public void setKey(T key) { 11 this.key = key; 12 } 13 }
1 package com.genericity.demo6; 2 3 import java.lang.reflect.Field; 4 5 public class Test2 { 6 public static void main(String[] args) { 7 Earase<Integer> integerEarase=new Earase<>(); 8 //利用反射,获取Earase类的字节码文件的class类对象 9 Class<? extends Earase> aClass = integerEarase.getClass(); 10 Field[] declaredFields = aClass.getDeclaredFields(); 11 for (Field declaredField : declaredFields) { 12 System.out.println(declaredField.getName()+":"+declaredField.getType().getSimpleName()); 13 } 14 } 15 } 16 //运行结果:key:Number
- 擦除方法中类型定义的参数
1 package com.genericity.demo6; 2 3 import java.util.List; 4 5 public class Earase<T extends Number> { 6 private T key; 7 8 public T getKey() { 9 return key; 10 } 11 12 public void setKey(T key) { 13 this.key = key; 14 } 15 16 /** 17 * 泛型方法 18 * @param t 参数也只能是List类型,或者是List类型的子类才行 19 * @param <T> 20 * @return 21 */ 22 public <T extends List> T show(T t){ 23 return t; 24 } 25 }
1 Method[] declaredMethods = aClass.getDeclaredMethods();//获取类中的所有方法 2 for (Method declaredMethod : declaredMethods) { 3 System.out.println(declaredMethod.getName()+":"+declaredMethod.getReturnType().getSimpleName()); 4 } 5 //运行结果: 6 //getKey:Number 7 //setKey:void 8 //show:List
- 桥接方法
1 package com.genericity.demo6; 2 3 /** 4 * 泛型接口 5 * @param <T> 6 */ 7 public interface Info<T> { 8 T info(T t); 9 }
1 package com.genericity.demo6; 2 3 public class InfoImpl implements Info<Integer> { 4 @Override 5 public Integer info(Integer value) { 6 return value; 7 } 8 }
1 InfoImpl info = new InfoImpl(); 2 Class<? extends InfoImpl> aClass1 = info.getClass(); 3 //当然,我们在获取类的字节码文件的时候,也可以直接使用.class的方式 Class<InfoImpl> aClass1=InfoImpl.class 4 Method[] declaredMethods1 = aClass1.getDeclaredMethods(); 5 for (Method method : declaredMethods1) { 6 System.out.println(method.getName()+":"+method.getReturnType().getSimpleName()); 7 } 8 9 //运行结果: 10 //info:Integer 11 //info:Object