try with resources用法【对象深度复制】

多个资源对象,则可以使用多个try catch捕获

package com.sxt;

import com.alibaba.fastjson.JSON;
import com.sxt.demian.Student;

import java.io.*;


/**
 * 深度复制对象
 */
public class ObjectCopy {

    public static void main(String[] args) {

        Student student=new Student("1","张三","三年级");

        Student student1=copyObject(student);

        System.out.println(JSON.toJSONString(student1));
    }

    /**
     * <T> 表明该方法将使用泛型类型T
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T copyObject(T t){

        T result=null;


        /**
         * 多个资源对象,则可以使用多个try catch捕获
         */
        try(

                //将对象转换为字节
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
                ObjectOutputStream oos=new ObjectOutputStream(bos)

        ){

            oos.writeObject(t);
            oos.flush();

            try (
                //将字节再转换为对象
                ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))
            ){

                result=(T)ois.readObject();

            } catch (IOException e) {
                e.printStackTrace();
            }


        }catch (Exception e){
            e.printStackTrace();
        }

/*

        try {

            //将对象转换为字节
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream out=new ObjectOutputStream(bos);

            out.writeObject(t);
            out.flush();
            bos.close();
            out.close();

            //将字节再转换为对象
            ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois=new ObjectInputStream(bis);

            result=(T)ois.readObject();
            ois.close();
            bis.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
*/

        return result;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值