List<Integer>添加一个String

利用反射魔法 就可以在 ArrayList 中添加一个 String类型的元素了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Test2 {
public static void main(String[] args) {
try {
List<Integer> test = new ArrayList<>();
test.add(1);
Method method = test.getClass().getMethod("add", Object.class);
method.invoke(test, "t");
for (Object num : test) {
System.out.println(num);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

输出结果为

1
2
1
t

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!