息得到Field的类型,并根据setting.xml设置它的值 。
private void setFieldValue(Object obj, Field field, String value) {
String fieldType = field.getType().getSimpleName();
try {
if (fieldType.equals("int"))
field.setInt(obj, new Integer(value));
else if (fieldType.equals("float"))
field.setFloat(obj, new Float(value));
else if (fieldType.equals("boolean"))
field.setBoolean(obj, new Boolean(value));
else if (fieldType.equals("char"))
field.setChar(obj, value.charAt(0));
else if (fieldType.equals("double"))
field.setDouble(obj, new Double(value));
else if (fieldType.equals("long"))
field.setLong(obj, new Long(value));
else
field.set(obj, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void setFieldValue(Object obj, Field field, List<String> value) {
try {
field.set(obj, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Java代码实现依赖注入(5)
时间:2011-07-22 51cto博客 zhangjunhd
5.测试
public static void main(String[] args) {
try {
BeanFactory factory = new BeanFactory();
factory.init("setting.xml");
Person p1 = (Person) factory.getBean("me");
System.out.print(p1.getName() + " ");
System.out.print(p1.getAge() + " ");
System.out.println(p1.getHeight());
Person p2 = (Person) factory.getBean("you");
System.out.print(p2.getName() + " ");
System.out.print(p2.getAge() + " ");
System.out.println(p2.getHeight());
ListOne list = (ListOne) factory.getBean("myList");
System.out.println(list.getMsg());
SetOne set = (SetOne) factory.getBean("mySet");
System.out.println(set.getMsg());
MapOne map = (MapOne) factory.getBean("myMap");
System.out.println(map.getMsg());
Persons us = (Persons) factory.getBean("us");
System.out.println(us.getI());
System.out.println(us.getU());
} catch (Exception e) {
e.printStackTrace();
}
}
测试结果:
ZJ 26 1.78
Mary 27 1.66
[java, c, windows]
[cat, tom, dog]
{c=CHINA, j=JAPAN, k=KOREA}
com.zj.ioc.di.imp.Person@1a5ab41
com.zj.ioc.di.imp.Person@18e3e60
本文出自 “子 孑” 博客,请务必保留此出处 http://zhangjunhd.blog.51cto.com/113473/126545
本文配套源码 |