package cn.reghao.tnb.search.esapp.util;

import java.lang.reflect.Field;

/**
 * @author reghao
 * @date 2023-04-05 16:50:42
 */
public class ClassUtil {
    public static Object getObject(Class<?> clazz, String[] strs) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        if (strs.length != fields.length) {
            return null;
        }

        Object object = clazz.getDeclaredConstructor().newInstance();
        for (int i = 0; i < fields.length; i++) {
            Class<?> clazzType = fields[i].getType();
            if (clazzType.equals(String.class)) {
                fields[i].setAccessible(true);
                fields[i].set(object, strs[i]);
            } else {
                Object result;
                if (clazzType.equals(Long.class)) {
                    result = Long.parseLong(strs[i]);
                } else if (clazzType.equals(Integer.class)) {
                    result = Integer.parseInt(strs[i]);
                } else {
                    result = Double.parseDouble(strs[i]);
                }

                fields[i].setAccessible(true);
                fields[i].set(object, result);
            }
        }
        return object;
    }
}
