Java基础-transient

  • transient关键字,防止关键对象的数据被序列化。

import java.io.*;
/**
 * Created by L on 2014/5/29.
 */
class MyTransient implements Serializable{
    String v1;
    transient String v2;
    static String v3;
    MyTransient(){
        v1 = "v1";
        v2 = "v2";
        v3 = "v3";
    }


    @Override
    public String toString(){
        System.out.println("v1 - " + v1 + ";  v2 - " + v2 + ";  v3 - " + v3);
        return "v1 - " + v1 + ";  v2 - " + v2 + ";  v3 - " + v3;
    }


    void mkSerialization(Object ob, String file){
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(ob);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    Object readSerialization(String file){
        Object ob = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            ob = ois.readObject();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return ob;
    }
}
class main{
    public static void main(String[] args){
        String file = "./mytransient3";
        MyTransient mt = new MyTransient();
        mt.mkSerialization(mt, file);
        MyTransient ob = (MyTransient) mt.readSerialization(file);
        mt.toString();
        ob.toString();
    }
}


文件序列化前后,transient关键字标注的变量v2有值,为空。防止重要数据被序列化后被盗取其中数据。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值