Java學習:反射的應用,依賴載入

我的襪子都是洞發表於2019-02-16

使用反射實現從配置檔案載入類以及根據配置檔案解決特定依賴關係。

配置檔案reflect.properties

1AdminDao=reflect.AdminDao
1GuestDao=reflect.GuestDao
1Manager=reflect.Manager
2Manager:AdminDao
2Manager:GuestDao
複製程式碼

對應類檔案AdminDao

package reflect;

public class AdminDao {
	public AdminDao(){
		System.out.println("成功例項化AdminDao");
	}
	
}
複製程式碼

對應類檔案GuestDao:

package reflect;

public class GuestDao {
	public GuestDao(){
		System.out.println("成功例項化GuestDao");
	}
}
複製程式碼

對應類檔案Manager:

package reflect;

public class Manager {
	private AdminDao adminDao = null;
	private GuestDao guestDao = null;
	public Manager() {
		System.out.println("Manage例項化成功");
	}
	public void setAdminDao (Object o) {
		this.adminDao = (AdminDao)o;
		System.out.println("解決adminDao依賴");
	}
	public void setGuestDao (Object o) {
		this.guestDao = (GuestDao)o;
		System.out.println("解決guestDao依賴");
	}
}
複製程式碼

反射測試工廠類:

package reflect;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ObjectFactory {
	public static Map<String,Object> map = new HashMap<String,Object>();
	
	static {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("src/reflect.properties"));
			String str = br.readLine();
			while(str != null) {
				char c = str.charAt(0);
				switch (c) {
					case '1':
						String[] arr = str.substring(1).split("=");
						Object o = Class.forName(arr[1]).newInstance();
						map.put(arr[0].trim().toLowerCase(), o);
						break;
					case '2':
						String[] arr2 = str.substring(1).split(":");
						Object obj = map.get(arr2[0].trim().toLowerCase());
						Object fieldObj = map.get(arr2[1].trim().toLowerCase());
						String methodName = "set"+arr2[1].substring(0, 1).toUpperCase()+arr2[1].substring(1);
						Method method = obj.getClass().getDeclaredMethod(methodName, Object.class);
						method.invoke(obj, fieldObj);
						break;
				}
				str = br.readLine();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public static void main(String[] args) {
		Set<String> set = map.keySet();
		for (String string:set) {
			System.out.println(string+"--"+map.get(string));
		}
	}

}

複製程式碼

跑起來結果:

成功例項化AdminDao
成功例項化GuestDao
Manage例項化成功
解決adminDao依賴
解決guestDao依賴
admindao--reflect.AdminDao@10d1f30
manager--reflect.Manager@7aacc1
guestdao--reflect.GuestDao@1e3cabd
複製程式碼

相關文章