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     } 
  • 相关阅读:
    Maxwell的vbs脚本转matlab
    maxwell电机直观理解
    maxwell电机转矩扫描与使用MTPA策略绘制效率map图
    maxwell施加均匀外磁场
    maxwell的那些坑&小技巧
    maxwell主从边界
    MySql基础
    数据结构知识结构框架图
    第八章 多线程
    软件
  • 原文地址:https://www.cnblogs.com/yuxuan/p/4142978.html
Copyright © 2011-2022 走看看