java之transient

transient关键字,表明一个属性是临时的,如果Class类实现了 Serializable接口,被transient修饰的属性不会被持久化!!!

代码验证:

public class TransientDemo implements Serializable {

    private static final long serialVersionUID = 1415782474432670389L;

    private String name;
    private transient String sex;

    public TransientDemo() {
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "TransientDemo{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public static void main(String[] args) throws IOException {
        String path = "D:"+ File.separator+"transientDemo.txt";
        File file = new File(path);

        TransientDemo transientDemo = new TransientDemo();
        transientDemo.setName("张三");
        transientDemo.setSex("保密:女");
        System.out.println("before: " + transientDemo);
        ObjectOutputStream output = null;
        try {
            output = new ObjectOutputStream(new FileOutputStream(file));
            output.writeObject(transientDemo);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            output.flush();
            output.close();
        }


        ObjectInput input = null;
        try {
            input = new ObjectInputStream(new FileInputStream(file));
            TransientDemo demo = (TransientDemo) input.readObject();
            System.out.println("after:  " + demo );

        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }finally {
            input.close();
        }
        /*  output----------------------------

        before: TransientDemo{name='张三', sex='保密:女'}
        after:  TransientDemo{name='张三', sex='null'}
        */
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值