通過屬性檔案的形式配置所需要的子類
首先建立一個fruit.properties的資源檔
內容為:
apple=Reflect.Apple
orange=Reflect.Orange
然後編寫主類代碼
//細節:命名規則:類,介面名稱都得大寫; // 寫完代碼記得格式化,就算是測試代碼,貼出來也是給人看的。不能太水。interface Fruit { void eat();}class Apple implements Fruit { public void eat() { System.out.println("Apple"); }}class Orange implements Fruit { public void eat() { System.out.println("Orange"); }}//操作屬性檔案類class Init { public static Properties getPro() throws IOException { Properties pro = new Properties(); File f = new File("fruit.properties"); if (f.exists()) { pro.load(new FileInputStream(f)); } else { pro.setProperty("apple", "Reflect.Apple"); pro.setProperty("orange", "Reflect.Orange"); pro.store(new FileOutputStream(f), "FRUIT CLASS"); } return pro; }}class Factory { public static Fruit getInstance(String className) { Fruit f = null; try { f = (Fruit) Class.forName(className).newInstance(); } catch (Exception e) { e.printStackTrace(); } return f; }}class Hello { public static void main(String[] a) throws IOException { Properties pro = Init.getPro(); Fruit f = Factory.getInstance(pro.getProperty("apple")); if (f != null) { f.eat(); } }}
【運行結果】:Apple
這裡就可以解釋以前看到.properties這種設定檔是幹嘛的啦,
估計大概就是這麼用的,讀取檔案配置,然後就可以修改設定檔的方式來簡單輕鬆的完成一些任務,串連資料的配置也是這樣的咯,大概有個印象,若要詳細瞭解,還得查一番才行。
mongo.properties
memcached.properties
map.properties
default_setting.properties
quartz.properties
在我的這個項目裡面就看到這麼幾個properties類型的檔案,原來這些就是存了一些系統配置啊。
原來如此。
Apple apple = (Apple) f;
咳咳,這個是不行的,人能不強轉成男人,至於為啥就自己猜吧。
編譯時間沒錯,運行時就炸了,這個也是多態的一個常問的問題。就不贅述啦
上面的代碼裡面有個問題。
雖然只是測試代碼,但是裡面的檔案流並沒有正確的關閉,
不知道觀眾的你是否發現啦,我也是回頭再看這個的時候才發現的,或者說是我在知道
如何正確的關閉檔案流之後,再看這個就看到了問題啦。
具體的就看下面這個文章
連結如下:
Java如何正確的使用try catch finally關閉檔案流的總結