Java序列化Transient关键字

      在有Transient关键字修饰的属性时,无论序列化时对该对象的相关属性是否改变,

      反序列化后该属性仍为默认值。

     比如一个Student类,如果有两个属性,private transient String name和 private int age,

     反序列化Student对象后name的属性总为Null。即便是定义成 private transient String name=“abcde”也是如此(这点和Static关键字是不同的)。如果private static String name=“abcde”,那么反序列化后该对象name的默认值为“abcde”。

测试代码如下:

Student类:

import java.io.Serializable;

public class Student implements Serializable {
 
    private  transient String name="abc";
    private  int 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 "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

序列化类:

import java.io.*;

public class SerializableDemo {
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		Student stu =new Student();
		stu.setAge(20);
		stu.setName("DuGuQiuBai");
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
		               new File("E:/Student.txt")));
		oos.writeObject(stu);
		System.out.println("Student对象序列化成功!");
		oos.close();
	}
}

反序列化类:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.text.MessageFormat;

public class AnotherProgram {

	public static void main(String[] args) throws IOException, Exception {
		// TODO Auto-generated method stub
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
				new File("E:/Student.txt")));
		Student student = (Student) ois.readObject();
		System.out.println("Student对象反序列化成功!");;
		System.out.println(student.getAge()+" : "+student.getName());
	}
	
}

测试结果为:

Student对象反序列化成功!
20 : null

 

 

你可能感兴趣的:(Java)