最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java如何用反射將一個對象復制給另一個對象

 更新時間:2023年09月25日 09:16:29   作者:YoungMirror  
這篇文章主要介紹了java如何用反射將一個對象復制給另一個對象問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

java用反射將一個對象復制給另一個對象

@SneakyThrows
    public static Object objectClone(Object newObject,Object oldObject){
        Field[] oldFields = oldObject.getClass().getDeclaredFields();
        Field newField;
        for (Field oldField : oldFields){
            oldField.setAccessible(true);
            newField = newObject.getClass().getDeclaredField(oldField.getName());
            newField.setAccessible(true);
            newField.set(newObject,oldField.get(oldObject));
        }
        return newObject;
    }

java復制一個對象使新對象和源對象值相同,地址不同

1. 實體(3個 模擬多層父級)支持多層父級和List,map的copy值

public class StudentDemo extends StudentF {
    private Integer stuId;
    private String stuName;
    private String stuPrice;
    private boolean flg;
    private List<String> listString;
    private HashMap<String, StuType> mapType;
    public HashMap<String, StuType> getMapType() {
        return mapType;
    }
    public void setMapType(HashMap<String, StuType> mapType) {
        this.mapType = mapType;
    }
    public List<String> getListString() {
        return listString;
    }
    public void setListString(List<String> listString) {
        this.listString = listString;
    }
    public boolean isFlg() {
        return flg;
    }
    public void setFlg(boolean flg) {
        this.flg = flg;
    }
    public StudentDemo(HashMap<String, StuType> mapType, List<StuType> listType, List<String> listString, Integer stuId, String stuName, String stuPrice, String stuSex, Integer stuAge, String stuNum, String stuTel, boolean isFlg) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuPrice = stuPrice;
        super.setStudentSex(stuSex);
        super.setStudentAge(stuAge);
        super.setStuNum(stuNum);
        super.setTel(stuTel);
        this.flg = isFlg;
        this.listString = listString;
        super.setListType(listType);
        this.mapType = mapType;
    }
    public StudentDemo(){}
    @Override
    public String toString() {
        return "StudentDemo{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuPrice='" + stuPrice + '\'' +
                ", stuSex='" + super.getStudentSex() + '\'' +
                ", stuAge='" + super.getStudentAge() + '\'' +
                ", stuNum='" + super.getStuNum() + '\'' +
                ", stuTel='" + super.getTel() + '\'' +
                ", flg='" + flg + '\'' +
                ", listString='" + listString + '\'' +
                ", listType='" + super.getListType() + '\'' +
                ", mapType='" + mapType + '\'' +
                '}';
    }
    public Integer getStuId() {
        return stuId;
    }
    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public String getStuPrice() {
        return stuPrice;
    }
    public void setStuPrice(String stuPrice) {
        this.stuPrice = stuPrice;
    }
}
public class StudentF extends StudentX {
    private String studentSex;
    private Integer studentAge;
    private List<StuType> listType;
    public List<StuType> getListType() {
        return listType;
    }
    public void setListType(List<StuType> listType) {
        this.listType = listType;
    }
    public String getStudentSex() {
        return studentSex;
    }
    public void setStudentSex(String studentSex) {
        this.studentSex = studentSex;
    }
    public Integer getStudentAge() {
        return studentAge;
    }
    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
}
public class StudentX {
    private String stuNum;
    private String Tel;
    public String getStuNum() {
        return stuNum;
    }
    public void setStuNum(String stuNum) {
        this.stuNum = stuNum;
    }
    public String getTel() {
        return Tel;
    }
    public void setTel(String tel) {
        Tel = tel;
    }
}

2. 工具類

package com.books.utils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 *  復制一個實體對象
 *  修改新對象時不影響源對象的值
 * @param <T> 項目中任意類型
 */
public class CopyObjectEntity<T> {
	/**
     *  復制實體方法
     * @param orderEntity 源對象
     * @param newEntity 新對象
     * @return 新對象
     */
    public T newPojo(Object orderEntity, Object newEntity){
        // 新對象
        T newPojo = null;
        try {
            // 源對象
            T orderPojo = (T)orderEntity;
            newPojo = (T)newEntity;
            // 獲取所有方法,包括父類
            Method[] orderObject = orderPojo.getClass().getMethods();
            // 遍歷所有方法
            for(int a = 0; a < orderObject.length; a ++){
                // 得到每一個方法名稱
                String name = orderObject[a].getName();
                // 判斷獲取需要的(普通的字段都是get/set),這里獲取get方法因為get到值才能賦值
                if(!name.equals("setClass") && !name.equals("class") && !name.equals("getClass") && name.startsWith("get")){
                    // 獲取方法
                    Method method = orderPojo.getClass().getMethod(name, new Class[] {});
                    // 執(zhí)行方法
                    Object value = method.invoke(orderPojo, new Object[] {});
                    // 拼接set方法
                    String aa = orderObject[a].getName().substring(3);
                    String bb = aa.substring(0, 1).toUpperCase();
                    String setter = bb + aa.substring(1);
                    // 創(chuàng)建描述器
                    PropertyDescriptor pd = new PropertyDescriptor(setter, newPojo.getClass());
                    //為上面聲明的字段設置set方法(又稱內(nèi)?。?
                    Method setMethod = pd.getWriteMethod();
                    // 執(zhí)行set
                    setMethod.invoke(newPojo, value);
                }
                // 判斷是boolean的字段get時為is
                if(!name.equals("setClass") && !name.equals("class") && !name.equals("getClass") && name.startsWith("is")){
                    Method method = orderPojo.getClass().getMethod(name, new Class[] {});
                    Object value = method.invoke(orderPojo, new Object[] {});
                    String aa = orderObject[a].getName().substring(2);
                    String bb = aa.substring(0, 1).toUpperCase();
                    String setter = bb + aa.substring(1);
                    PropertyDescriptor pd = new PropertyDescriptor(setter, newPojo.getClass());
                    //為上面聲明的字段設置set方法(又稱內(nèi)省)
                    Method setMethod = pd.getWriteMethod();
                    // 執(zhí)行set
                    setMethod.invoke(newPojo, value);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return newPojo;
    }
}

3. 測試

    public void test7(){
        List<String> ls = new ArrayList<>();
        ls.add("aa");
        ls.add("bb");
        ls.add("cc");
        List<StuType> listType = new ArrayList<>();
        listType.add(new StuType(1, "類型1"));
        listType.add(new StuType(2, "類型2"));
        HashMap<String, StuType> mapType = new HashMap<>();
        mapType.put("11", new StuType(11, "map1"));
        mapType.put("22", new StuType(22, "map2"));
        StudentDemo studentDemo = new StudentDemo(mapType, listType, ls,1, "aa" ,null, "男", 23, "010010", "15244669988", true);
        StudentDemo studentDemo1 = new StudentDemo();
        new CopyObjectEntity<StudentDemo>().newPojo(studentDemo, studentDemo1);
        System.out.println("復制完的新對象"+studentDemo1);
        studentDemo1.setStuId(22);
        studentDemo1.setStuName("你好啊");
        studentDemo1.setStuPrice("啦啦啦");
        studentDemo1.setStudentSex("女");
        studentDemo1.setStudentAge(20);
        studentDemo1.setStuNum("沒有學號");
        studentDemo1.setTel("沒有電話");
        studentDemo1.setFlg(false);
        List<String> ls1 = new ArrayList<>();
        ls1.add("33");
        ls1.add("44");
        ls1.add("55");
        List<StuType> listType1 = new ArrayList<>();
        listType1.add(new StuType(-1, "類型-1"));
        listType1.add(new StuType(-2, "類型-2"));
        HashMap<String, StuType> mapType1 = new HashMap<>();
        mapType1.put("11", new StuType(-11, "map-1"));
        mapType1.put("22", new StuType(-22, "map-2"));
        studentDemo1.setListType(listType1);
        studentDemo1.setMapType(mapType1);
        studentDemo1.setListString(ls1);
        System.out.println("源對象"+studentDemo);
        System.out.println("修改復制后對象"+studentDemo1);
        System.out.println("再次查看源對象"+studentDemo);
    }

4. 結(jié)果

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • java修改JFrame默認字體方式

    java修改JFrame默認字體方式

    這篇文章主要介紹了java修改JFrame默認字體方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • SpringBoot整合Redis、ApachSolr和SpringSession的示例

    SpringBoot整合Redis、ApachSolr和SpringSession的示例

    本篇文章主要介紹了SpringBoot整合Redis、ApachSolr和SpringSession的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • JAVA8 十大新特性詳解

    JAVA8 十大新特性詳解

    本教程將Java8的新特新逐一列出,并將使用簡單的代碼示例來指導你如何使用默認接口方法,lambda表達式,方法引用以及多重Annotation,之后你將會學到最新的API上的改進,比如流,函數(shù)式接口,Map以及全新的日期API
    2014-03-03
  • spring-boot中的SPI機制實例講解

    spring-boot中的SPI機制實例講解

    這篇文章主要介紹了spring-boot中的SPI機制實例講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • 詳解基于Spring Boot/Spring Session/Redis的分布式Session共享解決方案

    詳解基于Spring Boot/Spring Session/Redis的分布式Session共享解決方案

    本篇文章主要介紹了詳解基于Spring Boot/Spring Session/Redis的分布式Session共享解決方案 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • SpringBoot集成Sa-Token實現(xiàn)權(quán)限認證流程入門教程

    SpringBoot集成Sa-Token實現(xiàn)權(quán)限認證流程入門教程

    本文詳解SpringBoot集成Sa-Token框架的入門步驟,涵蓋依賴添加、配置設置、攔截器注冊、權(quán)限角色邏輯定義、設備工具類創(chuàng)建及登錄/注銷功能改造,通過注解實現(xiàn)鑒權(quán),解決權(quán)限認證問題,感興趣的朋友跟隨小編一起看看吧
    2025-09-09
  • Java使用XWPFDocument生成word文檔的示例代碼

    Java使用XWPFDocument生成word文檔的示例代碼

    XWPFDocument 是 Apache POI 庫中用于操作 .docx 格式 Word 文檔的核心類,本文將針對 XWPFDocument 進行詳細解析,涵蓋其核心功能、常見用法及實際開發(fā)中的關鍵點
    2025-12-12
  • SpringBoot中實現(xiàn)文件上傳、下載、刪除功能的步驟

    SpringBoot中實現(xiàn)文件上傳、下載、刪除功能的步驟

    本文將詳細介紹如何在 Spring Boot 中實現(xiàn)文件上傳、下載、刪除功能,采用的技術(shù)框架包括:Spring Boot 2.4.2、Spring MVC、MyBatis 3.5.6、Druid 數(shù)據(jù)源、JUnit 5 等,文中有詳細的操作步驟和示例代碼供大家參考,需要的朋友可以參考下
    2024-01-01
  • 深入理解Mybatis一級緩存

    深入理解Mybatis一級緩存

    客戶端向數(shù)據(jù)庫服務器發(fā)送同樣的sql查詢語句,如果每次都去訪問數(shù)據(jù)庫,會導致性能的降低,那么怎么提高呢?下面小編給大家分享下mybatis為我們提供了一級緩存的策略
    2016-12-12
  • java多線程之wait(),notify(),notifyAll()的詳解分析

    java多線程之wait(),notify(),notifyAll()的詳解分析

    本篇文章是對java多線程 wait(),notify(),notifyAll()進行了詳細的分析介紹,需要的朋友參考下
    2013-06-06

最新評論

蒙阴县| 潍坊市| 来凤县| 镇江市| 霍邱县| 梓潼县| 耒阳市| 通河县| 讷河市| 吉林省| 徐闻县| 正蓝旗| 嘉荫县| 巨野县| 织金县| 镇雄县| 唐河县| 大关县| 驻马店市| 封开县| 福鼎市| 凤阳县| 土默特右旗| 澄城县| 民乐县| 黎平县| 平利县| 广饶县| 丰都县| 清丰县| 莫力| 贵定县| 东平县| 喀喇| 兴和县| 深水埗区| 靖边县| 上犹县| 梁河县| 宜城市| 贡觉县|