xml获取对象工具类

package com.itheima.utils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

//获取xml文件的对象
public class XmlParserUtils2 {
    //这里f指定是xml文件
    public static <T> List<T> parse(String f, Class<T> cls, String sonElement) throws DocumentException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //反射出其类的变量
        Field[] declaredFields = cls.getDeclaredFields();

        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(new File(f));
        //根标签
        Element rootElement = read.getRootElement();
        //获得每一个子标签
        List<Element> elements = rootElement.elements(sonElement);
        //遍历每一个子标签
        for (Element element : elements) {
            System.out.println(element);
        }

        //该数组用于接收每个对象的属性值
        Object[] obj = new Object[declaredFields.length];

        //该数组是接收实体类构造器创建对象的参数
        String[] arr = new String[declaredFields.length];

        //该集合用于存取每个对象
        ArrayList<Object> objects = new ArrayList<>();

        //将对象的属性class的类型名添加到数组arr
        for (int i1 = 0; i1 < declaredFields.length; i1++) {
            arr[i1] = declaredFields[i1].getType().getName();
        }
        //遍历实体类对象的属性的class类型的字符串
        ArrayList<Class<?>> list = new ArrayList<>();
        for (String className : arr) {
            // 将字符串转换为Class对象
            Class<?> clazz = Class.forName(className);
            list.add(clazz);
        }
        Class<?>[] parameterTypes = list.toArray(new Class<?>[0]);
        Constructor<T> declaredConstructor = cls.getDeclaredConstructor(parameterTypes);
        System.out.println(declaredConstructor);
        declaredConstructor.setAccessible(true);

        //该集合收取每个xml的对象
        ArrayList<T> listObj = new ArrayList<T>();
        //该实体类有多少变量就获得其几个属性
        for (int i = 0; i < elements.size(); i++) {
            //从xml获得每一个子标签
            Element element = elements.get(i);
            //遍历每个子标签下的所有属性
            for (int j = 0; j < declaredFields.length; j++) {
                //暴力访问
                declaredFields[j].setAccessible(true);
                //获得每一个变量名
                String name = declaredFields[j].getName();
                //获得xml每个子标签内的某个属性的文本值
                String param = element.element(name).getText();
                System.out.println(param);
                //用数组存取当前用户的属性
                obj[j] = convertToType(param, declaredFields[j].getType());
            }
            T t = declaredConstructor.newInstance(obj);
            listObj.add(t);
        }

        return listObj;
    }

    private static Object convertToType(String value, Class<?> targetType) {
        try {
            if (targetType == String.class) {
                return value;
            } else if (targetType == Integer.class || targetType == int.class) {
                return Integer.parseInt(value);
            } else if (targetType == Boolean.class || targetType == boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (targetType == Double.class || targetType == double.class) {
                return Double.parseDouble(value);
            } else if (targetType == Float.class || targetType == float.class) {
                return Float.parseFloat(value);
            } else if (targetType == Long.class || targetType == long.class) {
                return Long.parseLong(value);
            } else {
                throw new IllegalArgumentException("Unsupported type: " + targetType);
            }
        } catch (NumberFormatException e) {
            // 处理转换失败的情况,例如返回默认值或抛出自定义异常
            System.err.println("Failed to convert value: " + value + " to type: " + targetType);
            return null; // 或者抛出自定义异常
        }
    }
}

你可能感兴趣的:(工具类)