Skip to content

Commit e81c3c6

Browse files
author
Andy
committed
通过反射来理解集合的泛型
1 parent 0c98b4c commit e81c3c6

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)