BeanUtil:将List中值按照指定位置封装到对象中

说明:为应付上级无脑需求,特地写出无脑代码。

自定义注解:

/**
 * @Author wen.jie
 * @Description 用于日期格式化
 * @Date 2021/2/1 21:04
 **/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FieldMapping {

    public String formatter() default "";
}

java实体类:

@Data
public class Dog {

    private String name;

    private Integer age;

    private long num;

    @FieldMapping(formatter = "yyyy/MM/dd HH:mm:ss")
    private Date date;

    private BigDecimal money;

    private char t;
}

配置文件file.properties:

dog.name=0
dog.age=1
dog.num=2
dog.date=3
dog.money=4
dog.t=5

BeanUtil工具类:

@Slf4j
@Component
public class BeanUtil implements InitializingBean {

    private static Properties prop = new Properties();

    @Override
    public void afterPropertiesSet() throws Exception {
        FileInputStream fis = new FileInputStream(ResourceUtils.getFile("classpath:file.properties"));
        prop.load(fis);
        fis.close();
    }

    /**
     * @Author wen.jie
     * @Description 我的代码不需要有可读性,自己能看懂就行了
     * @Date 2021/2/1 20:30
     **/
    public static<T> T newInstance(Class<T> clazz, List<String> filedList){
        T instance = null;
        try {
            instance = clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String key = encapsulatingKey(field, clazz);
                if(!prop.containsKey(key)) continue;
                String property = prop.getProperty(key);
                field.setAccessible(true);
                Class type = field.getType();
                String value = filedList.get(Integer.valueOf(property));
                if(type.equals(String.class)){
                    Method method = clazz.getMethod(getSetter(field.getName()), String.class);
                    method.invoke(instance, value);
                }else if(type.equals(Integer.class) || type == Integer.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Integer.TYPE ? Integer.TYPE : Integer.class);
                    method.invoke(instance, Integer.valueOf(value));
                }else if(type.equals(Date.class)){
                    FieldMapping annotation = field.getAnnotation(FieldMapping.class);
                    String formatter = annotation.formatter();
                    SimpleDateFormat sdf = new SimpleDateFormat(formatter);
                    Date date = sdf.parse(value);
                    Method method = clazz.getMethod(getSetter(field.getName()), Date.class);
                    method.invoke(instance, date);
                }else if(type.equals(Long.class) || type == Long.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Long.TYPE ? Long.TYPE : Long.class);
                    method.invoke(instance, Long.valueOf(value));
                }else if(type.equals(Boolean.class) || type == Boolean.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Boolean.TYPE ? Boolean.TYPE : Boolean.class);
                    Boolean flag = false;
                    if(value.equals("1") || "true".equals(value)) flag = true;
                    method.invoke(instance,flag);
                }else if(type.equals(Float.class) || type == Float.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Float.TYPE ? Float.TYPE : Float.class);
                    method.invoke(instance, Float.valueOf(value));
                }else if (type.equals(Double.class) || type == Double.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Double.TYPE ? Double.TYPE : Double.class);
                    method.invoke(instance, Double.valueOf(value));
                }else if(type.equals(Character.class) || type == Character.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Character.TYPE ? Character.TYPE : Character.class);
                    method.invoke(instance, value.charAt(0));
                }else if(type.equals(Short.class) || type == Short.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Short.TYPE ? Short.TYPE : Short.class);
                    method.invoke(instance, Short.valueOf(value));
                }else if(type.equals(Byte.class) || type == Byte.TYPE){
                    Method method = clazz.getMethod(getSetter(field.getName()), type == Byte.TYPE ? Byte.TYPE : Byte.class);
                    method.invoke(instance, Byte.valueOf(value));
                }else if(type.equals(BigDecimal.class)){
                    Class<BigDecimal> bigDecimalClazz = BigDecimal.class;
                    Constructor<BigDecimal> constructor = bigDecimalClazz.getConstructor(String.class);
                    BigDecimal bigDecimal = constructor.newInstance(value);
                    Method method = clazz.getMethod(getSetter(field.getName()), BigDecimal.class);
                    method.invoke(instance, bigDecimal);
                }
            }

        } catch (InstantiationException | NoSuchMethodException |IllegalAccessException | InvocationTargetException e) {
            log.error("reflect find exception");
        } catch (ParseException e) {
            log.error("date format find exception");
        }
        return instance;
    }

    private static <T> String encapsulatingKey(Field field, Class<T> clazz) {
        return clazz.getSimpleName().toLowerCase()+"."+field.getName();
    }

    private static String getSetter(String filedName){
        char[] cs= filedName.toCharArray();
        cs[0] = upper(cs[0]);
        return "set" + String.valueOf(cs);
    }

    private static char upper(char chars) {
        if (chars >= 97 && chars <= 122)
            chars ^= 32;
        return chars;
    }

}

测试:

    @Test
    void contextLoads() {
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("12");
        list.add("123213412");
        list.add("2020/01/02 21:23:56");
        list.add("12.3");
        list.add("o");
        Dog dog = BeanUtil.newInstance(Dog.class, list);
        System.out.println(dog);
    }

测试结果:

image-20210201210337803

原文地址:https://www.cnblogs.com/wwjj4811/p/14359026.html