使用反射实现从配置文件加载类以及根据配置文件解决特定依赖关系。
配置文件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