serialVersionUID&transient的使用

package com.czie.iot1913.lps.IO.ObjectStream;

import java.io.*;

/**
* FileName: ObjectStream
* Author: lps
* Date: 2022/3/28 17:45
* Sign:刘品水 Q:1944900433
* InvalidClassException
* 当序列化运行时检测到一个类中的下列问题之一时抛出。
* 类的串行版本与从流中读取的类的不匹配
* 该类包含未知的数据类型
* 班上没有一个可访问的无参数构造函数
*
* 给对象所处的类加个值 private static final long serialVersionUID = 42L;
*
*
* private transient int age;
*
*/
public class ObjectStreamDemo {
public static void main(String[] args) throws Exception {
//write();
read();
}
public static void write() throws Exception{
//ObjectOutputStream(OutputStream out)
//创建一个对象写入到指定的输出流。
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\JavaCode\\oos.txt"));
Student s1 = new Student("刘品水",21);
Student s2 = new Student();
//void writeObject(Object obj)
//写入指定的对象的对象。
oos.writeObject(s1);
//NotSerializableException
// 当一个实例需要实现Serializable接口。序列化运行时或实例类可以抛出此异常。参数应该是类的名称。
//一个类的串行化是由类实现java.io.serializable接口启用。类没有实现这个接口不会有任何序列化或反序列化其状态

oos.close();

}

public static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\JavaCode\\oos.txt"));
Object obj = ois.readObject();
Student s = (Student) obj;
//System.out.println(s);
System.out.println(s.getName()+","+s.getAge());
ois.close();
}
}


package com.czie.iot1913.lps.IO.ObjectStream;

import java.io.Serializable;

/**
* FileName: Student
* Author: lps
* Date: 2022/3/28 15:12
* Sign:刘品水 Q:1944900433
*/
public class Student implements Serializable {
private static final long serialVersionUID = 42L;


private String name;
// private int age;
private transient int age;


@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + 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;
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public Student() {
}
}

 

posted @ 2022-03-28 18:13  刘品水  阅读(24)  评论(0编辑  收藏  举报