File tree Expand file tree Collapse file tree
src/org/test/reflect/method Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package org .test .reflect .method ;
2+
3+ import java .lang .reflect .Method ;
4+ import java .util .ArrayList ;
5+
6+ /**
7+ * @author Andy
8+ * 通过反射来理解集合的泛型是怎么回事
9+ *
10+ */
11+ public class MethodDemo2 {
12+ public static void main (String [] args ) {
13+ ArrayList list1 = new ArrayList ();
14+ ArrayList <String > list2 = new ArrayList <String >();
15+ list2 .add ("hello" );
16+ // list2.add(100); //是错误的,泛型就是为了防止错误类型信息
17+ Class c1 = list1 .getClass ();
18+ Class c2 = list2 .getClass ();
19+ System .out .println (c1 ==c2 );
20+ // 反射的操作都是在编译之后的操作,即运行时刻
21+ /**
22+ * c1==c2结果返回true 说明编译之后的集合是去泛型化的
23+ * java 中集合的泛型,是防止错误输入数据的,只在编译时有效
24+ * 验证 :通过方法的反射来操作,绕过编译
25+ */
26+ try {
27+ Method m = c2 .getMethod ("add" , Object .class );
28+ m .invoke (list2 , 100 ); //绕过编译就绕过了泛型
29+ System .out .println (list2 .size ());
30+ System .out .println (list2 );
31+ } catch (Exception e ) {
32+ e .printStackTrace ();
33+ }
34+
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments