之前去面試的時候,被問到這個問題,那時候就說了用反射。然后面試官巴拉巴拉了,我回答不出來,然后就否認(rèn)掉自己的思路。今天實(shí)驗(yàn)一下是可以。
具體看demo:
public class ClassE {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
List<Integer> strList = new ArrayList<>();
strList.add(123);
strList.getClass().getMethod("add", Object.class).invoke(strList, "winney");
System.out.println("整數(shù):" + strList.get(0) + " 字符串:" + strList.get(1));
}
}
實(shí)驗(yàn)結(jié)果:

image.png