JAVA反射练习02

在配置文件中,配置要的目标类(全类名,该类必须有无参构造方法),和目标方法(名称)(无参方法)。
通过反射,调用目标类中的目标方法
假设该类中一定有默认无参构造方法

 1 package reflection;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 import java.lang.reflect.InvocationTargetException;
 7 import java.lang.reflect.Method;
 8 import java.util.Properties;
 9 
10 public class Practice2 {
11     public static void main(String args[]) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
12         String workingPath=System.getProperty("user.dir");
13         System.out.println("user.dir:"+workingPath);
14         //方式一
15       // callTargetMethod("C:\Users\73906\Desktop\AllinMove\wk4\practice\config.properties");
16          callTargetMethod("practice\config.properties");
17          //通过用户路径user.dir找到practice;
18         //practiceconfig.properties
19         //表示相遇路径,相对于practice文件下
20     }
21     /**
22      * @param configFilePath  表示配置文件的路径
23      */
24     public static void callTargetMethod(String configFilePath) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
25         //需要读取配置文件里面的信息
26         Properties properties = new Properties();
27         //创建一个字节输入流
28         FileInputStream fis = new FileInputStream(configFilePath);
29         //load方法,指向配置文件的输入流,读取配置文件内容, 并将其春初到Properties 对象中(key-value结构,全部都在)
30         properties.load(fis);
31         //通过属性名,获取属性值
32 
33 
34         //1. 读取配置文件信息,将去读取到我们的Properties对象中
35 
36         //2. 从Properties对象中,获取指定类的全类名和指定的方法名
37         String className = properties.getProperty("className");
38         String methodName = properties.getProperty("methodName");
39         /*System.out.println(className);
40         System.out.println(methodName);*/
41 
42         //3. 通过全类名,获取全类名所指定的类的,类型信息(通过访问其对应Class)
43         Class targetClass =  Class.forName(className);
44 
45         //4. 利用反射,targetClass中获取,目标方法(Method对象)
46         Method methodtoRflect = targetClass.getDeclaredMethod(methodName);
47 
48         //5. 利用反射,创建目标对象  Constructor对象.newInstance()
49             TargetClass2 obj = new TargetClass2();
50             methodtoRflect.setAccessible(true);
51         //6. Method对象.invoke(目标对象)
52         int res = (int) methodtoRflect.invoke(obj);
53         System.out.println("利用反射得到方法运行结果:"+res);
54 
55     }
56 }
57 
58 
59 class TargetClass2 {
60     private int test() {
61         int a=886;
62         return a;
63     }
64 
65 }
原文地址:https://www.cnblogs.com/debug-the-heart/p/13264091.html