通過反射運(yùn)行配置文件內(nèi)容

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();

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容