java 反射之越过泛型检查
2016-08-05 16:33
344 查看
反射之前,我们知道在集合类中一旦指定了泛型的类型,则只能在该集合中用该类型。但是我们可以利用反射机制来越过泛型检查。比如说利用反射机制获取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 + "]"; } }
相关文章推荐
- Java中通过反射越过泛型检查
- 通过反射越过泛型检查
- 反射-通过反射越过泛型检查
- Java反射技术绕过ArrayList泛型编译期间检查, 将不同类型数据存到一起
- 黑马程序员-------Java笔记--------怎么越过泛型检查
- 反射_通过反射越过泛型检查
- 利用反射越过集合的泛型检查
- 通过反射越过泛型检查
- Java使用反射技术越过泛型检测
- 利用反射越过泛型检查
- 反射越过泛型检查
- java反射之通过反射了解集合泛型的本质
- 通过取消Java检查使反射获得private
- Java基础增强3-反射,内省,beanutils,泛型
- java反射 获取 /List<实体> objData 泛型后的属性值
- Java反射与泛型(链接)
- JAVA常用基础知识点[继承,抽象,接口,静态,枚举,反射,泛型,多线程...]
- java 反射 子类泛型的class
- 黑马程序员——java高新技术(新特性、反射、泛型)
- JAVA的泛型与反射的联合应用