zoukankan      html  css  js  c++  java
  • java反射复制属性值

     1 /** 将sourceObj的属性拷贝到targetObj 
     2      * @param sourceObj 
     3      * @param targetObj 
     4      * @param clazz 从哪一个类开始(比如sourceObj对象层级为:Object->User->ChineseUser->ChineseMan->ChineseChongQingMan) 
     5      * 如果需要从ChineseUser开始复制,clazz就指定为ChineseUser.class 
     6      */  
     7     public static void cpoyObjAttr(Object sourceObj, Object targetObj, Class<?> clazz)throws Exception
     8     {  
     9         if(sourceObj==null || targetObj==null)
    10         {  
    11             throw new Exception("源对象和目标对象不能为null");  
    12         }  
    13         Field[] fields=clazz.getDeclaredFields();  
    14         for(int i = 0; i < fields.length; i++)
    15         {
    16             //System.out.println(fields[i].getName());
    17             //Object sourceValue=fields[i].get(sourceObj);  
    18             
    19             Method getMethod = sourceObj.getClass().getMethod("get" + fields[i].getName());
    20             Object sourceValue = (Object) getMethod.invoke(sourceObj, null);
    21             if(null==sourceValue)
    22             {
    23                 sourceValue = null;
    24             }            
    25             fields[i].setAccessible(true);          
    26             fields[i].set(targetObj,sourceValue);
    27            
    28 //            System.out.println(fields[i].getName()+";"+clazz+";"+fields[i].getType());            
    29 //            Method setMethod = targetObj.getClass().getMethod("set" +fields[i].getName(), fields[i].getType());
    30 //            setMethod.invoke(targetObj, sourceValue.toString());
    31         }  
    32         if(clazz.getSuperclass()==Object.class){  
    33             return;  
    34         }         
    35         cpoyObjAttr(sourceObj,targetObj,clazz.getSuperclass());             
    36     } 
  • 相关阅读:
    【Red Hat Linux基础】 磁盘分区详细教程
    分区间统计sql、删除重复数据
    sql 建立索引之前计算区分度
    jvm调优
    最短路径-迷宫类
    comparable and comparator 比较
    刷题之Implement strStr()、Climbing Stairs
    对线程池简单理解
    hash表系列(转)
    对于AVL树和红黑树的理解
  • 原文地址:https://www.cnblogs.com/yuxuan/p/4142978.html
Copyright © 2011-2022 走看看