一个对象只要实现了Serilizable接口就可以被序列化,该对象的属性和方法都会自动序列化,在属性前加关键字transient,该属性就不会被序列化。
- package com.testtransient.model;
- import java.io.Serializable;
- public class UserInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- private String name ;
- private transient String pwd ;
- public UserInfo(String name,String pwd){
- this.name =name;
- this.pwd =pwd;
- }
- public String toString(){
- return "name=" +name +",psw=" +pwd ;
- }
- }
- public class TestTransient {
- public static void main(String[] args) {
- UserInfouserInfo = new UserInfo("张三" , "123456" );
- System. out.println(userInfo);
- try {
- // 序列化,被设置为transient的属性没有被序列化
- ObjectOutputStreamo = new ObjectOutputStream(new FileOutputStream(
- "UserInfo.out"));
- o.writeObject(userInfo);
- o.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- try {
- // 重新读取内容
- ObjectInputStream in = new ObjectInputStream( new FileInputStream(
- "UserInfo.out"));
- UserInforeadUserInfo = (UserInfo) in.readObject();
- // 读取后psw的内容为null
- System. out.println(readUserInfo.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
输出结果:
name=张三,psw=123456
name=张三,psw=null