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