您的位置:首页 > 移动开发 > Objective-C

ObjectOutputStream and ObjectInputStream 序列化 transient

2019-06-11 19:14 1756 查看

对象                                        

内存------>硬盘文件中(序列化) ObjectOutputStream 序列化java对象  Serial

硬盘文件----->内存(反序列化将硬盘中的数据"反序列化 "到内存地址   DeSerial

Compile 编译(java------>class)       DeCompile 反编译

 

序列化 Serial

[code]import java.io.Serializable;//该接口是一个可序列化的    没有任何方法,是一个标识接口    像这样的接口还有Cloneable

public class User implements Serializable {
String name;

public User(String name) {
super();
this.name = name;
}

public String toString() {
return "User [name=" + name + "]";
}

}
[code]public class ObjectInputStream01 {
public static void main(String[] args) throws FileNotFoundException, IOException {
User u = new User("lili");

//创建流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\ppp\\qpqp.txt"));
//写
oos.writeObject(u);

oos.flush();
oos.close();
}
}

标识接口的作用,:标识的作用

JVM看到某个对象实现了标识接口会对它进行“特殊待遇”

待遇:会给该类添加一个属性,static final long serialVersionUID = (序列化版本号)
改变类会覆盖原有的序列化版本号

[code]public class User01 implements Serializable{
//自己写一个序列化版本号
static final long serialVersionUID = 123123132L;

String name;

}

 

不让系统自动生成,自己写一个序列化版本号

不管你的类如何升级,序列号都是一样的,就不会产生类的兼容问题

 

反序列化

[code]//反序列化
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\ppp\\qpqp.txt"));

//反序列化
Object o = ois.readObject();
System.out.println(o);

ois.close();

}

transient不参加序列化

因为transient不参加序列化,所以在ObjectInputStream反序列化的时候name = null;

[code]public class User01 implements Serializable{
//自己写一个序列化版本号
static final long serialVersionUID = 123123132L;

//如果不想让该属性参加序列化,需要使用transient修饰
transient String name;
User01 (String name){
this.name = name;
}
public String toString() {
return "User01 [name=" + name + "]";
}

}

 

 

 

 

 

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: