JavaSE-24.2.5【反射案例-越过泛型检查、运行配置文件中指定类的指定方法】
1 package day15.lesson2.p; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.ArrayList; 6 7 /* 8 2.10 反射练习 9 10 2.10.1 案例-越过泛型检查 11 通过反射技术,向一个泛型为Integer的ArrayList集合中添加一些字符串String数据 12 */ 13 public class Test1Reflect { 14 public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 15 ArrayList<Integer> arrayList = new ArrayList<>(); 16 17 arrayList.add(10); 18 arrayList.add(20); 19 // arrayList.add("hello"); //报错,编译异常 --> 即正常情况下无法在ArrayList<Integer>中添加String数据 20 21 //通过反射可以实现该功能 22 Class<? extends ArrayList> c = arrayList.getClass(); 23 Method add = c.getMethod("add", Object.class); //类型为Object-->那么通过反射在arrayList添加啥类型数据都行了QAQ 24 //反射可以越过泛型检查,获取到原始方法所需的参数类型 25 add.invoke(arrayList, "hello"); 26 add.invoke(arrayList, "world"); 27 add.invoke(arrayList, "java"); 28 29 System.out.println(arrayList); //[10, 20, hello, world, java] 30 } 31 }
1 package day15.lesson2.p; 2 3 public class Student { 4 public void study(){ 5 System.out.println("好好学习天天向上"); 6 } 7 }
1 package day15.lesson2.p; 2 3 public class Teacher { 4 public void teach(){ 5 System.out.println("好好教书"); 6 } 7 }
1 package day15.lesson2.p; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import java.lang.reflect.Constructor; 7 import java.lang.reflect.InvocationTargetException; 8 import java.lang.reflect.Method; 9 import java.util.Properties; 10 11 /* 12 2.10.2 案例-运行配置文件中指定类的指定方法 13 */ 14 public class Test2Reflect { 15 public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { 16 /*Student student = new Student(); 17 student.study(); //好好学习天天向上 18 Teacher teacher = new Teacher(); 19 teacher.teach(); //好好教书*/ 20 21 /* 22 自定义配置文件 23 class.txt 24 className=xxx (注意此处类名应为带包全路径) 25 methodName=xxx 26 */ 27 Properties properties = new Properties(); 28 FileReader fr = new FileReader("stage2\\src\\day15\\lesson2\\p\\class.txt"); 29 properties.load(fr); 30 fr.close(); 31 System.out.println(properties); //{methodName=study, className=day15.lesson2.p.Student} 32 33 String className = properties.getProperty("className"); 34 String methodName = properties.getProperty("methodName"); 35 System.out.println(className + "," + methodName); //day15.lesson2.p.Student,study 36 37 //通过反射使用 从配置文件中获取的配置信息 38 Class<?> c = Class.forName(className); 39 Constructor<?> con = c.getConstructor(); 40 Object obj = c.newInstance(); 41 Method method = c.getMethod(methodName); 42 method.invoke(obj); 43 /* 44 className=day15.lesson2.p.Student 45 methodName=study 46 --> 好好学习天天向上 47 48 className=day15.lesson2.p.Teacher 49 methodName=teach 50 --> 好好教书 51 */ 52 } 53 }
className=day15.lesson2.p.Teacher methodName=teach