1.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <application> <beans> <bean name="obj1" class="com.jzy.xml.class1"> <attribute name="attr1">value1</attribute> </bean> <bean name="obj2" class="com.jzy.xml.class2"> <attribute name="attr1">value1</attribute> </bean> </beans> </application>
2.自定义异常类:
package com.jzy.ioc;
public class BeanNotFindException extends RuntimeException{
public BeanNotFindException(){
super("你要查找的bean不存在!");
}
}
3.属性保存类:
package com.jzy.ioc;
import java.util.Hashtable;
public class IocBeanInfo {
String className="";
Hashtable attrMapping=new Hashtable();
}
4.主类(xml解析,内省,反射)
package com.jzy.ioc;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Hashtable;
import javax.sound.midi.MidiDevice.Info;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class IocFactory {
Hashtable beanMapping = new Hashtable();
public IocFactory() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // 定义工厂
// API,使应用程序能够从
// XML
// 文档获取生成
// DOM
// 对象树的解析器。
dbf.setNamespaceAware(true); // 指示是否将工厂配置为生成具有感知名称空间功能的解析器。
DocumentBuilder db = dbf.newDocumentBuilder(); // 定义 API, 使其从 XML
// 文档获取 DOM 文档实例
Document doc = db.parse("myclass.xml"); //xml文件在根路径下
NodeList beansList = doc.getElementsByTagName("beans"); //获取beans节点集合
for (int i = 0; i < beansList.getLength(); i++) {
Node beansNode = beansList.item(i); //获取具体的beans节点
NodeList beanList = beansNode.getChildNodes(); //获取具体的beans节点的子节点的集合(bean)
for (int j = 0; j < beanList.getLength(); j++) {
Node beanNode = beanList.item(j); //获取具体的bean节点
if (beanNode.getNodeName().equals("bean")) { //因为xml会将空格,换行也当成节点,所以要判断
IocBeanInfo info = new IocBeanInfo();
String beanName = ""; //保存bean节点属性中name的值
NamedNodeMap beanNodeMap = beanNode.getAttributes();
Node beanNameAttr = beanNodeMap.getNamedItem("name");
beanName = beanNameAttr.getNodeValue(); //保存属性名
Node beanClassAttr = beanNodeMap.getNamedItem("class");
info.className = beanClassAttr.getNodeValue(); //保存类名
NodeList attributeList = beanNode.getChildNodes();
for (int m = 0; m < attributeList.getLength(); m++) {
Node attributeNode = attributeList.item(m);
if (attributeNode.getNodeName().equals("attribute")) {
String attrValue = "";
NamedNodeMap attrNodeMap = attributeNode
.getAttributes();
Node attributeName = attrNodeMap
.getNamedItem("name");
attrValue = attributeNode.getTextContent()
.trim();
// System.out.println("attrName: "+attributeName.getNodeName());
// System.out.println("attrValue: "+attributeNode.getTextContent().trim());
info.attrMapping
.put(attributeName.getNodeValue(),
attrValue);
}
}
beanMapping.put(beanName, info);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getBean(String baseName) {
if (beanMapping.get(baseName) != null) {
IocBeanInfo info = (IocBeanInfo) beanMapping.get(baseName);
try {
Class cl = Class.forName(info.className); //获取类描述信息
Object obj = cl.newInstance(); //创建对象
BeanInfo binfo = Introspector.getBeanInfo(cl); //内省获取属性信息
PropertyDescriptor[] pds = binfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String pname = pd.getName();
if (info.attrMapping.get(pname) != null) {
Method propertyWriteMethod = pd.getWriteMethod();
Class[] argsTypes = propertyWriteMethod
.getParameterTypes();
String argTypeString = argsTypes[0].getCanonicalName();
String attValue = info.attrMapping.get(pname)
.toString();
if (argTypeString.equals("int")) {
// 利用反射调用该属性的set方法
propertyWriteMethod.invoke(obj,
new Object[] { new Integer(attValue) });
} else if (argTypeString.equals("boolean")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Boolean(attValue) });
} else if (argTypeString.equals("char")) {
propertyWriteMethod.invoke(
obj,
new Object[] { new Character(attValue
.charAt(0)) });
} else if (argTypeString.equals("byte")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Byte(attValue) });
} else if (argTypeString.equals("short")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Short(attValue) });
} else if (argTypeString.equals("long")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Long(attValue) });
} else if (argTypeString.equals("double")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Double(attValue) });
} else if (argTypeString.equals("float")) {
propertyWriteMethod.invoke(obj,
new Object[] { new Float(attValue) });
} else if (argTypeString.equals("java.lang.String")) {
propertyWriteMethod.invoke(obj,
new Object[] { attValue });
} else {
Object refObj = getBean(attValue);
propertyWriteMethod.invoke(obj,
new Object[] { refObj });
}
}
}
return obj;
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
throw new BeanNotFindException();
}
return null;
}
public static void main(String[] args){
IocFactory factory=new IocFactory();
IocBeanInfo info=(IocBeanInfo)factory.beanMapping.get("obj1");
System.out.println(info.className);
}
}
转载于:https://blog.51cto.com/jiangzhiyong/1251250