会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132365个问题
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 37816楼

老师,该如何理解:序列化不能保存任何成员方法和静态的成员变量 

对此我还特意去写了一下

源码:

    自定义一个可以序列化的类除了get set 方法 还特意加了两个测试方法:

package com.sxt.obj;


import java.io.Serializable;

public class Student implements Serializable{
	private int id;
	private String name;
	public Student(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Student() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String returntest() {//增加测试方法
		return "return ...";
	}
	public void voidTest() {//增加测试方法
		System.out.println("void ....");
	}
}

    2、写入

package com.sxt.obj;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class StudentWrite {
	public static void main(String[] args) {
		Student stu = new Student(1001, "张三");
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(
					new BufferedOutputStream(
							new FileOutputStream("student.txt")));
			oos.writeObject(stu);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

    3、读取

package com.sxt.obj;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class StudnentRead {
	public static void main(String[] args) throws ClassNotFoundException {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(
					new BufferedInputStream(
							new FileInputStream("student.txt")));
			Student stu = (Student) ois.readObject();
			String str = stu.returntest();
			System.out.println(str);
			stu.voidTest();
			System.out.println(stu.getId() + ", " + stu.getName());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}


读取后还是可以使用对象的方法

image.png

源码:

ObjStreamPro.7z


最后,感觉方法还是保存了???

JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 37818楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术(旧) 37819楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 37822楼
Python 全系列/第五阶段:数据库编程/mysql的使用 37824楼
Python 全系列/第五阶段:数据库编程/mysql的使用 37826楼
Python 全系列/第五阶段:数据库编程/mysql的使用 37828楼
JAVA 全系列/第四阶段:网页编程和设计/Jquery(旧) 37829楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 37830楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637