【Java筆記】通過反射配置檔案執行類中的方法
阿新 • • 發佈:2018-11-21
要求:在一個Test類中呼叫不同類中的方法,不改動Test原始碼,如何做到?
實現方法:將要執行的類名和方法名,以鍵值對的形式卸儲存在文字中,執行哪個類就讀取配置檔案即可。
實現步驟:1.準備配置檔案,鍵值對
2.IO流讀取(Reader)配置檔案
3.檔案中鍵值對儲存到集合Properties
4.反射獲取類的Class檔案物件
5.Class檔案物件獲取指定方法
6.執行方法
配置檔案內容如下:
className=Person
methodName=method
實現程式碼:
public class Test { public static void main(String[] args) throws Exception { // 通過Properties集合從檔案中讀取資料 Properties prop = new Properties(); // 讀取檔案中的資料到集合中 prop.load(new FileInputStream("properties.txt")); // 獲取鍵所對應的值 String className = prop.getProperty("className"); System.out.println(className); // 1,獲取Person.class 位元組碼檔案物件 Class c = Class.forName(className); // 2,獲取構造方法 // public Person(String name, int age, String address) Constructor con = c.getConstructor(String.class, int.class, String.class); // 3,建立物件 Object obj = con.newInstance("小明", 20, "中國"); System.out.println(obj); // 4,獲取指定的方法 // private void method5(){} String methodName = prop.getProperty("methodName"); Method m5 = c.getDeclaredMethod(methodName, null); // 5,開啟暴力訪問 m5.setAccessible(true); // 6,執行找到的方法 m5.invoke(obj, null); } }
在實際開發中,改動原始碼是大忌,因此我們在不改動原始碼的情況下,可以通過反射來實現或者替換其他擴充套件功能,只需要改動配置檔案中的內容即可,反射是框架的靈魂,比如Spring框架就是基於反射機制,通過修改配置檔案來實現需求, 所以學好反射能更加清楚地瞭解Spring框架。