Java高新技術之架構的概念及用反射技術開發架構的原理和設定檔

來源:互聯網
上載者:User

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

四、設定檔管理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.