簡單的反射框架應用

  通過以上幾篇文章,已經知道反射是什麼,大概是怎麼用,接下來用反射做一個簡單的實例模擬框架運行原理


配置文件config.xml的代碼如下

<?xml version="1.0" encoding="UTF-8"?> 
<beans> 
    <bean id="javaBean" class="javatribe.fts.reflection.JavaBean"> 
       <property name="userName"> 
           <value>馮先生</value> 
       </property> 
       <property name="password"> 
           <value>88888888</value> 
       </property> 
    </bean> 
</beans> 
然後建立一個JavaBean

package javatribe.fts.reflection;

public class JavaBean {
	private String userName; 
    private String password;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	} 

}

接下來建立一個BeanFactory這是bean工廠,學習過Spring框架大體都會有所瞭解的了

package javatribe.fts.reflection;

import java.io.InputStream; 
import java.lang.reflect.Method; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 
import org.dom4j.Attribute; 
import org.dom4j.Document; 
import org.dom4j.Element; 
import org.dom4j.io.SAXReader;

public class BeanFactory { 
    private Map<String, Object> beanMap = new HashMap<String, Object>(); 
    /** 
    * bean工廠的初始化. 
    * @param xml xml配置文件 
    */ 
    public void init(String xml) { 
           try { 
                  //讀取指定的配置文件 
                  SAXReader reader = new SAXReader(); 
                  ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
                  //從class目錄下獲取指定的xml文件 
                  InputStream ins = classLoader.getResourceAsStream(xml); 
                  Document doc = reader.read(ins); 
                  Element root = doc.getRootElement();   
                  Element foo; 
                  
                  //遍歷bean 
                  for (Iterator i = root.elementIterator("bean"); i.hasNext();) {   
                         foo = (Element) i.next(); 
                         //獲取bean的屬性id和class 
                         Attribute id = foo.attribute("id");   
                         Attribute cls = foo.attribute("class"); 
                         
                         //利用Java反射機制,通過class的名稱獲取Class對象 
                         Class bean = Class.forName(cls.getText()); 
                         
                         //獲取對應class的信息 
                         java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean); 
                         //獲取其屬性描述 
                         java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); 
                         //設置值的方法 
                         Method mSet = null; 
                         //創建一個對象 
                         Object obj = bean.newInstance(); 
                         
                         //遍歷該bean的property屬性 
                         for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) {   
                                Element foo2 = (Element) ite.next(); 
                                //獲取該property的name屬性 
                                Attribute name = foo2.attribute("name"); 
                                String value = null; 
                                
                                //獲取該property的子元素value的值 
                                for(Iterator ite1 = foo2.elementIterator("value"); ite1.hasNext();) { 
                                       Element node = (Element) ite1.next(); 
                                       value = node.getText(); 
                                       break; 
                                } 
                                
                                for (int k = 0; k < pd.length; k++) { 
                                       if (pd[k].getName().equalsIgnoreCase(name.getText())) { 
                                              mSet = pd[k].getWriteMethod(); 
                                              //利用Java的反射極致調用對象的某個set方法,並將值設置進去 
                                              mSet.invoke(obj, value); 
                                       } 
                                } 
                         } 
                         
                         //將對象放入beanMap中,其中key爲id值,value爲對象 
                         beanMap.put(id.getText(), obj); 
                  } 
           } catch (Exception e) { 
                  System.out.println(e.toString()); 
           } 
    } 
    
    /** 
    * 通過bean的id獲取bean的對象. 
    * @param beanName bean的id 
    * @return 返回對應對象 
    */ 
    public Object getBean(String beanName) { 
           Object obj = beanMap.get(beanName); 
           return obj; 
    } 
    
    /** 
    * 測試方法. 
    * @param args 
    */ 
    public static void main(String[] args) { 
           BeanFactory factory = new BeanFactory(); 
           factory.init("config.xml"); 
           JavaBean javaBean = (JavaBean) factory.getBean("javaBean"); 
           System.out.println("userName=" + javaBean.getUserName()); 
           System.out.println("password=" + javaBean.getPassword()); 
    } 
} 

最後輸出結果是

userName=馮先生
password=888888




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章