读取xml文件,根据文件的配置创造出对应的实例,并通过反射设置对象的属性

读取xml文件,根据文件的配置创造出对应的实例,并通过反射设置对象的属性
package com.liuguangfa.fanshe; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ReaderXML { /** * 读取xml文件,根据文件的配置创造出对应的实例,并通过反射设置对象的属性 * * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws NoSuchFieldException * @throws DocumentException */ public static void readerXml() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, DocumentException { // 创建员工集合接受读取到的员工数据 List<Employees> employees = new ArrayList<>(); // 创建文件对象 File file = new File("D:/employees.xml"); // SAXReader reader = new SAXReader(); // 读取根节点 Document doc = null; doc = reader.read(file); // 获取根节点 Element root = doc.getRootElement(); // 获取子节点 List<Element> elements = root.elements(); for (Element i : elements) { String id = i.attributeValue("id"); Element name = i.element("name"); String nameString = name.getText(); Element age = i.element("age"); String ageString = age.getText(); Element sex = i.element("sex"); String sexString = sex.getText(); // 通过反射的方式去构建对象 Class<?> clazz = Class.forName("com.liuguangfa.fanshe.Employees"); // 调用构造函数进行构造对象 // Employees emp = (Employees) clazz.getConstructor().newInstance(String.class,String.class,String.class,String.class); // Employees emp = new Employees(null, null, null, null); Employees emp = (Employees) clazz.getConstructor(String.class,String.class,String.class,String.class).newInstance(null,null,null,null); // 通过反射进行成员属性进行赋值 Field field = clazz.getDeclaredField("name"); field.setAccessible(true); field.set(emp, nameString); // 通过反射通过set方法及逆行你赋值 Method method = clazz.getMethod("setAge", String.class); method.invoke(emp, ageString); // 通过私有的成员属性进行赋值 field = clazz.getDeclaredField("sex"); field.setAccessible(true); field.set(emp, sexString); // 再次通过方法进行赋值 method = clazz.getMethod("setId", String.class); method.invoke(emp, id); // 添加员工到集合 employees.add(emp); } System.out.println(employees); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, DocumentException { readerXml(); } }
文章原文地址:刘广法,转载保留出处,感谢