反射之前,我们知道在集合类中一旦指定了泛型的类型,则只能在该集合中用该类型。但是我们可以利用反射机制来越过泛型检查。比如说利用反射机制获取ArrayList中的add()方法,再调用add方法时,就会越过泛型检查,只是由于泛型检查是在编译时期进行的,也就是说编译后的add()方法其实和没有指定泛型的add()方法是一致的,都是不能进行泛型检查的。所以通过反射获取ArrayList的Class文件对象中的add()方法,在调用该add()方法时是不用泛型检查的。如下所示:
测试主类
package cn.edu.tju.versace;
import java.lang.reflect.Method;
import java.util.ArrayList;
import cn.edu.tju.reflect.Student;
/**
* 反射越过泛型检查
* @author feige
*/
public class ReflectDemo {
public static void main(String[] args) throws Exception {
ArrayList<Integer> arrayList=new ArrayList<Integer>();//指定泛型为Integer
Class c=arrayList.getClass();//获取Class文件对象
Method addMethod=c.getDeclaredMethod("add",Object.class);//获取Class文件对象中的add()方法
Student s=new Student("arui",25);
addMethod.invoke(arrayList, "afei");//越过泛型检查,添加String类型
addMethod.invoke(arrayList, s);//越过泛型检查,添加Student类型
System.out.println(arrayList);//结果为:[afei, Student [name=arui, age=25]]
}
}
Student类:
package cn.edu.tju.reflect;
public class Student {
private String name;
public int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
private Student() {
super();
}
private void showName(String name) {
this.name=name;
System.out.println("name is:"+name);
}
public int showAge() {
return age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}