1. 反射機制:在泛型為Integer的ArrayList中存放一個String類型的對象
package test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class TestReflect1 { /** * 反射機制:在泛型為Integer的ArrayList中存放一個String類型的對象 * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { List<Integer> list = new ArrayList<Integer>(); Method method = list.getClass().getMethod("add", Object.class); method.invoke(list, 1); method.invoke(list, 2); method.invoke(list, "Java反射機制測試"); method.invoke(list, 3); System.out.println(list); } }
運行結果:
2. 反射機制:在泛型為String的ArrayList中存放一個integer類型的對象
package test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class TestReflect2 { /** * 反射機制:在泛型為String的ArrayList中存放一個integer類型的對象 * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { List<String> list = new ArrayList<String>(); Method method = list.getClass().getMethod("add", Object.class); method.invoke(list, "Java反射機制測試"); method.invoke(list, "Java反射機制測試"); method.invoke(list, 1); method.invoke(list, "Java反射機制測試"); System.out.println(list); } }
運行結果:
3. 反射機制:在泛型為Map的ArrayList中存放一個integer/String/HashMap類型的對象
package test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestReflect3 { /** * 反射機制:在泛型為Map的ArrayList中存放一個integer/String/HashMap類型的對象 * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { List<Map<String, Object>> list = new ArrayList<>(); Method method = list.getClass().getMethod("add", Object.class); method.invoke(list, 1); method.invoke(list, "Java反射機制測試"); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "zhangsan"); map.put("sex", "男"); method.invoke(list, map); System.out.println(list); } }
運行結果: