zoukankan      html  css  js  c++  java
  • 对象转化 复制相同属性

    /**
    * 对象转化(自动构造新对象,并复制相同属性的数据)
    *
    * @param o
    * @param targetC
    * @return
    */
    @SuppressWarnings("unchecked")
    public static <T> T parseObject(Object o, Class<T> targetC) {
    Object targetO = null;
    if (o == null) {
    return (T) targetO;
    }
    try {
    // 1.构造新对象
    targetO = targetC.newInstance();
    Field[] targetFields = targetC.getDeclaredFields();
    // 2.向新对象写数据(循环读取老对象中数据写入新对象)
    for (Field f : o.getClass().getDeclaredFields()) { // 循环处理类属性
    if (!Modifier.isStatic(f.getModifiers())) {// 非静态变量才做处理
    try {
    // 2.1.读数据
    Method rm = getMethod(f.getName(), o.getClass());// 获得读方法
    Object val = rm.invoke(o);// 调用读方法
    // 2.2.写数据
    for (Field targetF : targetFields) {
    if (f.getName().equals(targetF.getName())) {// 属性名相同
    try {
    Method wm = setMethod(targetF.getName(), targetC);// 获得写方法
    wm.invoke(targetO, val);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return (T) targetO;
    }
  • 相关阅读:
    深入理解Http协议
    Http协议详解
    过滤器、监听器、拦截器的区别
    HTTP状态代码集
    理解XML-RPC
    Axis2 解析
    REST SOAP XML-RPC分析比较
    Spring 第一天课程
    Spring 框架学习 有用
    数据库主从复制,读写分离,负载均衡,分表分库的概念 没用
  • 原文地址:https://www.cnblogs.com/pxzbky/p/14837620.html
Copyright © 2011-2022 走看看