Java中transient关键字

transient的作用
Java中的transient关键字,transient是短暂的意思。对于transient 修饰的成员变量,在类的实例对象的序列化处理过程中会被忽略。 因此,transient变量不会贯穿对象的序列化和反序列化,生命周期仅存于调用者的内存中而不会写到磁盘里进行持久化。
Java 的transient关键字为我们提供了便利,只需要实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。像用户的密码、银行卡、敏感数据等等。

package org.bc.offer.base;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TransientTest {
    public static void main(String [] args){
        try {
            Student student = new Student("zhangsan", 18);

            System.out.println(student);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d://test.txt"));

            oos.writeObject(student);

            oos.close();

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://test.txt"));

            Student student1 = (Student) ois.readObject();

            System.out.println(student1);
        }catch (Exception e){

        }


    }
}
class Student implements Serializable

{

    private String name = null;

    private transient int age = 0;

    Student(String name, int age)

    {

        this.name = name;

        this.age = age;

    }

    public String getName()

    {

        return name;

    }

    public void setName(String name)

    {

        this.name = name;

    }

    public int getAge()

    {

        return age;

    }

    public void setAge(int age)

    {

        this.age = age;

    }

    @Override

    public String toString()

    {

        return "name is " + getName() + " and age is " + getAge();

    }


name is zhangsan and age is 18
name is zhangsan and age is 0

Process finished with exit code 0

你可能感兴趣的:(读书笔记,java,jvm,开发语言)