[導入]題目: IOC 后臺機制學習
說明,這是從BeanSoft的blog上看到的,上面提供了代碼,我看過之后,自己按照那個思路又理了一遍,增加記憶。
給定:
配置文件 config.txt, 文件內容
該文件中的三個值會隨時可能變化, 唯一不變的是 className 指定的都是一個 JavaBean,field制定該javaBean的屬性value指定該屬性的值。
要求: 寫一段代碼, 讀取配置文件 config.txt, 然后實現把 className 指定的 JavaBean 類加載(注意這個類名是可以修改的, 可配置的), 然后生成一個實例,
并把配置文件中field字段指定的值作為這個實例的屬性名(這里是name)所對應的值設置為 網易博客(字符串), 并且要讀出最后設置的值.
代碼:
1.假定一個Bean:
2實際讀取數據
給定:
配置文件 config.txt, 文件內容
className = com.example.MyBean field = name value = 網易博客 |
該文件中的三個值會隨時可能變化, 唯一不變的是 className 指定的都是一個 JavaBean,field制定該javaBean的屬性value指定該屬性的值。
要求: 寫一段代碼, 讀取配置文件 config.txt, 然后實現把 className 指定的 JavaBean 類加載(注意這個類名是可以修改的, 可配置的), 然后生成一個實例,
并把配置文件中field字段指定的值作為這個實例的屬性名(這里是name)所對應的值設置為 網易博客(字符串), 并且要讀出最后設置的值.
代碼:
1.假定一個Bean:
package com.example; public class MyBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
2實際讀取數據
package com.example; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.*; import java.lang.reflect.Method; import java.util.Properties; public class IocStudy { Properties pop = new Properties(); public void loadConfig(File file) throws IOException{ FileInputStream fis = new FileInputStream(file); pop.load(fis); fis.close(); } public void setValue(String className, String field, String value) throws Exception { Class bean = Class.forName(className); Object obj = bean.newInstance(); BeanInfo info = Introspector.getBeanInfo(bean); PropertyDescriptor[] pds =info.getPropertyDescriptors(); for(PropertyDescriptor pd : pds){ if(pd.getName().equalsIgnoreCase(field)){ Method rm = pd.getReadMethod(); Method wm = pd.getWriteMethod(); wm.invoke(obj, value); System.out.println("設置的值是:"+rm.invoke(obj, null)); break; } } } private File getConfig(String fileName){ String filePath = this.getClass().getClassLoader().getResource("").toString(); filePath = filePath.substring(0, filePath.indexOf("classes")-1)+"/"; System.out.println(filePath); File file = new File(filePath+fileName); return file; } /** * @param args */ public static void main(String[] args) throws Exception { IocStudy ioc = new IocStudy(); ioc.loadConfig(ioc.getConfig("config.xml")); ioc.setValue(ioc.pop.getProperty("className"), ioc.pop.getProperty("field"), ioc.pop.getProperty("value")); } } |
文章來源:http://huxiaofei590.blog.163.com/blog/static/3259612200711611955728
posted on 2007-12-06 11:10 ThinkInJava 閱讀(134) 評論(0) 編輯 收藏