java关键字篇

java关键字篇

transient

transient 将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会被序列化

code 实例

//User 序列化对象实体类
import java.io.Serializable;

/**
 * 序列化对象
 * transient 将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会被序列化
 */
public class User implements Serializable {
    private static final long serializableUid = 123456L;
    // transient 关键字修饰
    private transient int age;
    private String name;

    /**
     * getter and setter
     */
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

// Test测试类
import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Serializable();
        DeSerializable();
    }

    /**
     * @deprecated 反序列化对象方法
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static void DeSerializable() throws IOException, ClassNotFoundException {
        File file = new File("W://javaSE_file/Lee");
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
        User newUser = (User) objectInputStream.readObject();
        System.out.println("age 添加了 transient ! 反序列化之后" + newUser.getAge());
    }

    /**
     * @deprecated 序列化对象方法
     * @throws IOException
     */
    private static void Serializable() throws IOException {
        User user = new User();
        user.setName("触碰@阳光");
        user.setAge(20);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("W://javaSE_file/Lee"));
        objectOutputStream.writeObject(user);
        objectOutputStream.close();
        System.out.println("age 添加了 transient ! 序列化之前" + user.getAge());
    }


}


// 执行后,文件出现序列化对象文件
// 添加 transient 关键字的属性并没有被反序列化解析出来
// || console 打印日志
age 添加了 transient ! 序列化之前20
age 添加了 transient ! 反序列化之后0

Process finished with exit code 0
// 执行后,文件出现序列化对象文件
// 没有添加 transient 关键字的属性并没有被反序列化解析出来
// || console 打印日志
age 添加了 transient ! 序列化之前20
age 添加了 transient ! 反序列化之后20

Process finished with exit code 0

transient 可以选择性的对实体类进行序列化组织

posted @ 2020-09-20 10:15  触碰A阳光  阅读(121)  评论(0编辑  收藏  举报