import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/*
* 报文以及请求解析
*
* */
public class Templet {
static Map<String, String> map = new HashMap<String, String>();
/*
* xml映射实体Bean;
* 根据实体Bean属性,注入XML字节文本;
* !仅限获取标签内文本!!!
* @ xml 需要解析的XML字符串
* @ t 需要映射的实体Bean
*
* */
public static <T> T xmlToBean(String xml,T t)
throws DocumentException, SecurityException, InstantiationException, IllegalAccessException {
Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element root = doc.getRootElement(); // 获取根节点
Map<String, String> map = getElement(root);
Field[] fields = t.getClass().getDeclaredFields();
String[] name = new String[fields.length];
Field.setAccessible(fields, true);
for (int i = 0; i < name.length; i++) {
name[i] = fields[i].getName();
setFieldValue(t, name[i], map.get(name[i]));
}
// 赋值后需要清空map
map.clear();
return t;
};
/**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*/
public static void setFieldValue(final Object obj, final String fieldName,final Object value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
}
}
/**
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
*
* 如向上转型到Object仍无法找到, 返回null.
*/
public static Field getAccessibleField(final Object obj,
final String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class;
superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);//没有字段的时候 继续向上寻找
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {// NOSONAR
// Field不在当前类定义,继续向上转型
}
}
return null;
}
/*
* @param root 当前节点
* 递归获取当前节点下的所有内容
*/
public static Map<String, String> getElement(Element root) {
Iterator ri = root.elementIterator();// 父节点迭代器
while (ri.hasNext()) {
Element foo = (Element) ri.next();// 下一个二级节点
map.put(foo.getName(), foo.getText());
getElement(foo);
}
return map;
}
}