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


    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) });
            }
        }
    
    }
  • 相关阅读:
    分享图片到在线服务
    获取和保存照片
    处理图片(updated)
    简化版“询问用户是否退出”
    捕获高像素照片(updated)
    处理高像素的照片
    加强版照片捕获
    图片拍摄、处理、镜头应用
    Windows Phone 推送通知的第四类推送
    网络通信
  • 原文地址:https://www.cnblogs.com/chenghu/p/5582780.html
Copyright © 2020-2023  润新知