an", new BeanHandler());
saxReader.read(file);
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
}
3.ElementHandler,dom4j的ElementHandler接口有两个方法,一个是onStart(),它主要用于处理该 元素的属性以及动态增加新的Handler类;另一个是onEnd(),它主要用于获得该元素的Text文本以及删除 已添加的Handler。
BeanHandler
private class BeanHandler implements ElementHandler {
Object obj = null;
public void .Start(ElementPath path) {
Element beanElement = path.getCurrent();
Attribute classAttribute = beanElement.attribute("class");
Class<?> bean = null;
try {
bean = Class.forName(classAttribute.getText());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Field fields[] = bean.getDeclaredFields();
Map<String, Field> mapField = new HashMap<String, Field>();
for (Field field : fields)
mapField.put(field.getName(), field);
try {
obj = bean.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
path.addHandler("property", new PropertyHandler(mapField, obj));
}
public void .End(ElementPath path) {
Element beanElement = path.getCurrent();
Attribute idAttribute = beanElement.attribute("id");
beanMap.put(idAttribute.getText(), obj);
path.removeHandler("property");
}
}
Java代码实现依赖注入(4)
时间:2011-07-22 51cto博客 zhangjunhd
PropertyHandler
private class PropertyHandler implements ElementHandler {
Map<String, Field> mapField;
Object obj;
public PropertyHandler(Map<String, Field> mapField, Object obj) {
this.mapField = mapField;
this.obj = obj;
}
public void .Start(ElementPath path) {
Element propertyElement = path.getCurrent();
Attribute nameAttribute = propertyElement.attribute("name");
path.addHandler("value", new ValueHandler(mapField, obj,
nameAttribute));
path.addHandler("list", new ListHandler(mapField, obj,
nameAttribute));
path.addHandler("set", new SetHandler(mapField, obj,
nameAttribute));
path.addHandler("map", new MapHandler(mapField, obj,
nameAttribute));
path.addHandler("ref", new RefHandler(mapField, obj,
nameAttribute));
}
public void .End(ElementPath path) {
path.removeHandler("value");
path.removeHandler("list");
path.removeHandler("set");
path.removeHandler("map");
path.removeHandler("ref");
}
}
根据setting.xml,我们可以得到各种注入元素的Handler类处理流程图。
4. setFieldValue()基于反射机制和相应的类信 |