1、架構與架構要解決的核心問題
我做房子賣給使用者住,由使用者自己安裝門窗和空調,我做的房子就是架構,使用者需要使用我的架構,把門窗插入進我提供的架構中。架構與工具類有區別,工具類被使用者的類調用,而架構則是調用使用者提供的類。
2、架構要解決的核心問題
我在寫架構(房子)時,你這個使用者可能還在上小學,還不會寫程式呢?我寫的架構程式怎樣能調用到你以後寫的類(門窗)呢?
因為在寫才程式時無法知道要被調用的類名,所以,在程式中無法直接new 某個類的執行個體對象了,而要用反射方式來做。
3、綜合案例
- 先直接用new 語句建立ArrayList和HashSet的執行個體對象,示範用eclipse自動產生 ReflectPoint類的equals和hashcode方法,比較兩個集合的運行結果差異。
- 然後改為採用設定檔加反射的方式建立ArrayList和HashSet的執行個體對象,比較觀察運行結果差異。
- elipse對資源檔的管理
config.properties 設定檔的內容:className1=java.util.ArrayList
className2=java.util.HashSet
public class ReflectPoint{ public int x; public int y;public ReflectPoint(int x, int y){super();this.x = x;this.y = y;}public String toString(){return this.x+" "+this.y;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;final ReflectPoint other = (ReflectPoint) obj;if (x != other.x)return false;if (y != other.y)return false;return true;}}
import java.util.*;import java.io.*;public class ReflectTest2{public static void main(String[] args)throws Exception{ //一定要記住用完整的路徑,但完整的路徑不是寫入程式碼,而是運算出來的。//如:工程目錄/內部所在路徑//InputStream in=new FileInputStream("config.properties"); //使用類的載入器擷取流//InputStream in=ReflectTest2.class.getClassLoader().getResourceAsStream("day01/config.properties");/*一個類載入器能載入.class檔案,那它當然也能載入classpath環境下的其他檔案,既然它有如此能力,它沒有理由不順帶提供這樣一個方法。它也只能載入classpath環境下的那些檔案。注意:直接使用類載入器時,不能以/打頭。*/InputStream in=ReflectTest2.class.getResourceAsStream("resources/config.properties");Properties prop=new Properties();prop.load(in);in.close();//關閉系統資源//String className1=prop.getProperty("className1");String className2=prop.getProperty("className2");//Collection collections=(Collection)Class.forName(className1).newInstance();Collection collections=(Collection)Class.forName(className2).newInstance();ReflectPoint rp1=new ReflectPoint(3,3);ReflectPoint rp2=new ReflectPoint(5,6);ReflectPoint rp3=new ReflectPoint(3,3);collections.add(rp1);collections.add(rp2);collections.add(rp3);collections.add(rp1);System.out.println("collections:"+collections.size());}}
四、設定檔管理