import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class DynamicCollectionExample { public static void main(String[] args) throws Exception { Class<?> arrayListClass = Class.forName("java.util.ArrayList"); List<String> list = (List<String>) arrayListClass.newInstance(); Method method = list.getClass().getMethod("add", Object.class); method.invoke(list, "Hello"); method.invoke(list, "World"); for (Object element : list) { System.out.println(element); } } }


上一篇:
下一篇:
切换中文