transient 关键字的简单用法

  我们都知道一个对象只要实现了Serilizable接口,这个对象就可以被序列化。

在实际中我们可能会遇到有部分属性需要序列化,部分属性不需要序列化的问题,这时需要使用transient来做。

main方法如下:

package com.examplexue;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class main {
    public static void main(String[] args){

        testClass test = new testClass();
        test.setTest1("test1");
        test.setTest2("test2");
        //输出读取前设置的字符
        System.out.println("test1: " + test.getTest1());
        System.err.println("test2: " + test.getTest2());

        try {
            //创建文件test.txt
            ObjectOutputStream os = new ObjectOutputStream(
                    new FileOutputStream("D:/test.txt"));
            os.writeObject(test); // 将test对象写进文件
            os.flush();
            os.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("===========================================");
        //下面是输出文件内容
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(
                    "D:/test.txt"));
            test = (testClass) is.readObject(); // 从流中读取User的数据
            is.close();
            //输出从文件中取出
            System.out.println("test1: " + test.getTest1());
            System.err.println("test2: " + test.getTest2());

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



类testClass如下:

package com.examplexue;

import java.io.Serializable;

public class testClass implements Serializable {
    private String test1;

    private transient String test2;

    public void setTest1(String test1) {
        this.test1 = test1;
    }

    public void setTest2(String test2) {
        this.test2 = test2;
    }

    public String getTest1() {

        return test1;
    }

    public String getTest2() {
        return test2;
    }
}


输出结果如下:


test1: test1
test2: test2
===========================================
test2: null
test1: test1



以上就是 transient 关键字的简单用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值