标签:java java对象序列化 null 理解 ber tac object 参考 imp
对于一个实体对象,不想将所有的属性都进行序列化,有专门的关键字 transient:
private transient String name;
当对该类序列化时,会自动忽略被 transient 修饰的属性
当然该对象反序列话的时候也就不存在这个name属性值了
public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN;//这个值不会被序列化传过去 public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }
注意 ObjectOutputStream 类的 writeObject(Object obj ) 方法,这个方法可以序列化一个对象
import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); }catch(IOException i) { i.printStackTrace(); } } }
注意 ObjectInputStream 的 readObject() 方法,可以反序列化对象
import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); /** *Deserialized Employee... Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101 */ } }
序列化就是把一个原本存储在堆Heap中的存储得略复杂的信息 序列化成一个.ser文件,方便存储和传输;
为了保存对象在内存中的状态(对象类型、数据类型、数据值这些),并且可以把保存的对象读出来;
参考链接:
https://www.cnblogs.com/sunhaoyu/p/4581282.html
标签:java java对象序列化 null 理解 ber tac object 参考 imp
原文地址:https://www.cnblogs.com/sangong/p/9581868.html