我创建了一个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"));
- }
- }
复制代码 异常提示:
请大牛们给指点一下!
|
|