进阶day10-.static和transient在序列化中的区别与作用

This commit is contained in:
2026-03-23 16:42:56 +08:00
parent 822f7b4810
commit b6b5c8ab39
3 changed files with 5 additions and 3 deletions

View File

@@ -21,7 +21,7 @@ public class Demo11 {
Student s = new Student("张三", 20);
//序列化将java对象保存到文件中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student2.txt"));
oos.writeObject(s);
oos.close();

View File

@@ -18,7 +18,7 @@ import java.util.function.Supplier;
public class Demo12 {
//将之前的student.txt读取到java进程中生成一个叫张三18的Student对象
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student2.txt"));
Object o = ois.readObject();
if (o instanceof Student) {
Student s = ((Student) o);

View File

@@ -6,7 +6,9 @@ Serializable接口的作用起到一个标识的作用确认当前类的
*/
public class Student implements Serializable {
String name;
int age;
transient int age;//transient:瞬态,在序列化对象时,被它修饰的属性,不能被保存
static String classroom = "1903";//不会被序列化,静态内容跟着字节码文件,只跟类有关
public Student(String name, int age) {
this.name = name;