黑马程序员技术交流社区
标题:
谁给解决一下一个异常
[打印本页]
作者:
韩伟
时间:
2012-8-1 10:50
标题:
谁给解决一下一个异常
我创建了一个Student类,然后用ObjectOutPutStream写入流,结果出现了一个NotSerializableException异常:具体代码如下
Student类:
class Student implements Comparable<Student>
{
private String name;
private int age;
private String num;
public Student() {}
public Student(String name, int age, String num)
{
this.name = name;
this.age = age;
this.num = num;
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public void setNum(String num)
{
this.num = num;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String getNum()
{
return num;
}
public void show()
{
System.out.println("name:"+name+" age:"+age+" num:"+num);
}
public int hashCode()
{
return num.hashCode();
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("不是Student类");
Student s = (Student)obj;
return this.getName().equals(s.getName())&&this.getAge() == s.getAge();
}
public int compareTo(Student s)
{
int n = this.getName().compareTo(s.getName());
if(0 == n)
return s.getAge() - this.getAge();
return n;
}
}
复制代码
写入的代码:
import java.io.*;
class ObjectStreamDemo
{
public static void main(String []args) throws IOException
{
oosWrite();
}
public static void oosWrite() throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f:\\obj.txt"));
oos.writeObject(new Student("孙悟空",1280,"花果山001"));
}
}
复制代码
异常提示:
QQ截图20120801104926.png
(3.71 KB, 下载次数: 30)
下载附件
2012-8-1 10:49 上传
请大牛们给指点一下!
作者:
陈淑飞
时间:
2012-8-1 10:54
异常提示都很明确了,说Student 没有实现 java.io.Serializable 接口呢
作者:
周坤
时间:
2012-8-1 11:06
Student类没有实现Serializable接口,
只需要class Student implements Comparable<Student> , Serializable就行了。
当然还要导入import java.io.Serializable;
作者:
余清兰
时间:
2012-8-1 11:13
ObjectInputStream与ObjectOutputStream 被操作的对象需要实现Serializable(标记接口即没有方法的接口)
这样这个类就会生成一个ID号,这个ID号是系统通过成员变量和成员函数计算出来的,用来标识这个类
如果你生成对象后,把对象序列化了(比如存到硬盘的文件里),你又修改了类里的成员,再反序列化时(读取文件里的对象到内存中)
就会失败,因为修改了类里的成员,ID号就变了,与之前对象序列化时的就不一样了,就报错
有一种方法可以解决这个问题,可以在最开始定义类时自定义一个UID号:pubic static final long serialVersionUID = 42L; (注:42L这个值可以任意定义)
注:静态变量是不能被序列化的,因为它存储在方法区,而对象存在堆内存中,只能序列化堆内存中的数据。
如果非静态成员也不想序列化,就加关键字transient修饰,保证其值在堆内存中存在,而不在文件中存在。
作者:
韩伟
时间:
2012-8-1 11:21
我明白了,真是谢谢大家了!{:soso_e183:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2