通过反射运行配置文件内容

https://mp.weixin.qq.com/s/rji3J3-TxmW7Zvqu7nZuYw

student类:

public class Student {  
    public void show(){  
        System.out.println("is show()");  
    }  
}

配置文件以txt文件为例子(pro.txt):[温馨提醒:pro.txt 配置文件中的类名和方法名后面都不能有空格,否则会抛出 NotFound 异常,这点不太好排查(特别是编辑器不显示空格字符的情况下)]

className = cn.fanshe.Student  
methodName = show 

测试类:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

/*
 * 我们利用反射和配置文件,可以使:应用程序更新时,对源码无需进行任何修改
 * 我们只需要将新类发送给客户端,并修改配置文件即可
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        //通过反射获取Class对象  
        Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"  
        //2获取show()方法  
        Method m = stuClass.getMethod(getValue("methodName"));//show  
        //3.调用show()方法  
        m.invoke(stuClass.getConstructor().newInstance());

    }

    //此方法接收一个key,在配置文件中获取相应的value  
    public static String getValue(String key) throws IOException{
        Properties pro = new Properties();//获取配置文件的对象  
        FileReader in = new FileReader("pro.txt");//获取输入流  
        pro.load(in);//将流加载到配置文件对象中  
        in.close();
        return pro.getProperty(key);//返回根据key获取的value值  
    }
}  

控制台输出:
is show()
需求:
当我们升级这个系统时,不要Student类,而需要新写一个Student2的类时,这时只需要更改pro.txt的文件内容就可以了。代码就一点不用改动

要替换的student2类:

public class Student2 {  
    public void show2(){  
        System.out.println("is show2()");  
    }  
} 

配置文件更改为:

className = cn.fanshe.Student2  
methodName = show2  

控制台输出:
is show2();

你可能感兴趣的:(通过反射运行配置文件内容)