List<String>转换为实体类的属性【转】

Posted on   jiaoqing。  阅读(1118)  评论(0编辑  收藏  举报
复制代码
package model;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ListToModel {
    public static void main(String[] args) {
        List<Object> userList = new ArrayList<Object>();
        userList.add("ooP");
        userList.add("男");
        userList.add(18);
        User user = new User();
        try {
            listToModel(userList, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user.getName() + "; " + user.getGender() + "; " + user.getAge());

    }

    public static <T> void listToModel(List<Object> list, T t) throws Exception {
        Field[] fields = t.getClass().getDeclaredFields();
        if (list.size() != fields.length) {
            return;
        }
        for (int k = 0, len = fields.length; k < len; k++) {
            // 根据属性名称,找寻合适的set方法
            String fieldName = fields[k].getName();
            String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);
            Method method = null;
            Class<?> clazz = t.getClass();
            try {
                method = clazz.getMethod(setMethodName, new Class[] { list.get(k).getClass() });
            } catch (SecurityException e1) {
                e1.printStackTrace();
                return;
            } catch (NoSuchMethodException e1) {
                String newMethodName = "set" + fieldName.substring(0, 1).toLowerCase()
                        + fieldName.substring(1);
                try {
                    method = clazz.getMethod(newMethodName, new Class[] { list.get(k).getClass() });
                } catch (SecurityException e) {
                    e.printStackTrace();
                    return;
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                    return;
                }
            }
            if (method == null) {
                return;
            }
            method.invoke(t, new Object[] { list.get(k) });
        }
    }

}
复制代码

 

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

随笔 - 287, 文章 - 0, 评论 - 3, 阅读 - 42万

Copyright © 2025 jiaoqing。
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示