起因:
有个人看到我写了一段代码:
[code="java"]
// 获得名称创建实例
private Object creatNewExample(String className) {
try {
Class c = Class.forName(className);
return c.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
[/code]
说:这不是IOC
我问:IOC不是通过它实现的吗?
他答:这是装载,哪里是IOC。
但是,我代码还没写完呢!
所以,完成后的代码:
[code="java"]
//容器
private static HashMap hashmap = new HashMap();
ReadXml rx;
public IocContent() {
}
public IocContent(String path) {
rx = new ReadXml(path);
// 获得XML生成的MAP
HashMap<String, String> xmlMap = rx.loadInfo();
manageBean(xmlMap);
}
// 返回所需实例
public Object getBean(String id) {
return hashmap.get(id);
}
// 从XML中获得需要生成实例并且将其放入容器中
private void manageBean(HashMap<String, String> map) {
Iterator<String> it = map.keySet().iterator();
// 循环获得XML中的个个值
while (it.hasNext()) {
String temp = it.next();
Object object = creatNewExample(map.get(temp));
hashmap.put(temp, object);
}
}
// 获得名称创建实例
private Object creatNewExample(String className) {
try {
Class c = Class.forName(className);
return c.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
[/code]
我的思路是:
由装载-->可以生成实例的IOC-->可以生成实例又可以赋值的IOC(这个还没做到)
我现在不知道,我写的这段代码是不是IOC。我被此人弄糊涂了!谁帮我解释下。