All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.houbb.iexcel.hutool.support.read.DefaultMapToBeanReader Maven / Gradle / Ivy

There is a newer version: 1.6.0
Show newest version
package com.github.houbb.iexcel.hutool.support.read;

import cn.hutool.core.collection.CollectionUtil;
import com.github.houbb.heaven.util.lang.reflect.ClassUtil;
import com.github.houbb.heaven.util.util.MapUtil;
import com.github.houbb.iexcel.hutool.annotation.ExcelField;
import com.github.houbb.iexcel.hutool.exception.ExcelException;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 默认实现
 * @param  泛型
 */
public class DefaultMapToBeanReader implements MapToBeanReader {

    @Override
    public T readToBean(Class tClass, Map map) {
        try {
            T instance = ClassUtil.newInstance(tClass);
            if(MapUtil.isEmpty(map)) {
                return instance;
            }

            // 考虑使用 cache
            List fields = ClassUtil.getAllFieldList(tClass);
            if(CollectionUtil.isEmpty(fields)) {
                return instance;
            }

            for(Field field : fields) {
                Object object = getFieldReadValue(field, map);
                if(object == null) {
                    continue;
                }

                field.setAccessible(true);

                //TODO: 后续使用 convert 优化
                String text = object.toString();
                field.set(instance, text);
            }

            return instance;
        } catch (Exception e) {
            throw new ExcelException(e);
        }
    }

    /**
     * 获取对应的读取自
     * @param field 字段
     * @param map map
     * @return 结果
     */
    private static Object getFieldReadValue(Field field, Map map) {
        ExcelField excelField = field.getAnnotation(ExcelField.class);
        if(excelField == null) {
            return null;
        }
        if(!excelField.readRequire()) {
            return null;
        }

        String headerName = excelField.headerName();
        return map.get(headerName);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy