Java反射超越泛型
BeanUtils.copyProperties引发的血案
在一次使用BeanUtils.copyProperties的方法是,莫名其妙的报错,产生的代码分解如下:
1 |
|
在运行这段代码的时候,发生了异常的信息:
对于这个异常,我观察了很久,在调试的时候发现,EntityA中的UniteA中的字段竟然能够赋值给 EntityB中UnitB中的字段!! 类型不一样,竟能够存储!!
泛型仅仅适用于编译期
对于这个问题,归根于Java的泛型的特点,泛型仅仅适用于编译期,下面我们写几个代码来验证这个问题:
List<String> strList=new ArrayList<>();
strList.add("1234");//正常的编译
strList.add(1234);//编译不能通过
上面的例子我们可以看到List
List<String> strList=new ArrayList<>();
strList.add("1234");//正常的编译
try {
Method method=strList.getClass().getDeclaredMethod("add",Object.class);
method.invoke(strList,1234);
System.out.println(strList);
} catch (Exception e) {
e.printStackTrace();
}
调试信息如下:
同样,我们也可以使用如下代码验证上面的结论:
List<String> strList=new ArrayList<>();
List<Integer> intList=new ArrayList<>();
System.out.println(strList.getClass().equals(intList.getClass()));
`
打印结果为:true
本文代码文件:下载