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 配置文件中的類名和方法名后面都不能有空格,否則會(huì)拋出 NotFound 異常,這點(diǎn)不太好排查(特別是編輯器不顯示空格字符的情況下)]
className = cn.fanshe.Student
methodName = show
測(cè)試類:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;
/*
* 我們利用反射和配置文件,可以使:應(yīng)用程序更新時(shí),對(duì)源碼無需進(jìn)行任何修改
* 我們只需要將新類發(fā)送給客戶端,并修改配置文件即可
*/
public class Demo {
public static void main(String[] args) throws Exception {
//通過反射獲取Class對(duì)象
Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"
//2獲取show()方法
Method m = stuClass.getMethod(getValue("methodName"));//show
//3.調(diào)用show()方法
m.invoke(stuClass.getConstructor().newInstance());
}
//此方法接收一個(gè)key,在配置文件中獲取相應(yīng)的value
public static String getValue(String key) throws IOException{
Properties pro = new Properties();//獲取配置文件的對(duì)象
FileReader in = new FileReader("pro.txt");//獲取輸入流
pro.load(in);//將流加載到配置文件對(duì)象中
in.close();
return pro.getProperty(key);//返回根據(jù)key獲取的value值
}
}
控制臺(tái)輸出:
is show()
需求:
當(dāng)我們升級(jí)這個(gè)系統(tǒng)時(shí),不要Student類,而需要新寫一個(gè)Student2的類時(shí),這時(shí)只需要更改pro.txt的文件內(nèi)容就可以了。代碼就一點(diǎn)不用改動(dòng)
要替換的student2類:
public class Student2 {
public void show2(){
System.out.println("is show2()");
}
}
配置文件更改為:
className = cn.fanshe.Student2
methodName = show2
控制臺(tái)輸出:
is show2();