老师,该如何理解:序列化不能保存任何成员方法和静态的成员变量
对此我还特意去写了一下
源码:
自定义一个可以序列化的类除了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();
}
}
}
}
}
读取后还是可以使用对象的方法

源码:
ObjStreamPro.7z
最后,感觉方法还是保存了???