日期:2014-05-20  浏览次数:20734 次

求助:一个java中的序列化机制
在java中,一个父类(SpuerC)没有实现serivalizable接口,它的子类(SubC)怎么样才能序列化?

我的程序如下,运行时产生如下错误:

java.io.NotSerializableException:   InherSerialTest2.SubC
at   java.io.ObjectOutputStream.writeObject0(Unknown   Source)
at   java.io.ObjectOutputStream.writeObject(Unknown   Source)
at   InherSerialTest2.InherSerialTest2.main(InherSerialTest2.java:21)

怎么样才能让SubC能序列化?


程序源码如下:

SuperC   类:

package   InherSerialTest2;

public   abstract   class   SuperC   {

int   supervalue;

public   SuperC(int   supervalue)   {
super();
//   TODO   Auto-generated   constructor   stub
this.supervalue   =   supervalue;
}

public   SuperC(){//必须要有无参构造函数

}

public   int   getSupervalue()   {
return   supervalue;
}

public   void   setSupervalue(int   supervalue)   {
this.supervalue   =   supervalue;
}

public   String   toString()   {
//   TODO   Auto-generated   method   stub
return   "supervalue   :   "   +   supervalue;
}

}


SubC   类

package   InherSerialTest2;

import   java.io.IOException;
import   java.io.ObjectInputStream;

import   InherSerialTest.SuperA;

public   class   SubC   extends   SuperC   {

private   int   subvalue;

public   SubC(int   supervalue,   int   subvalue)   {
super(supervalue);
//   TODO   Auto-generated   constructor   stub
this.subvalue   =   subvalue;
}

public   int   getSubvalue()   {
return   subvalue;
}

public   void   setSubvalue(int   subvalue)   {
this.subvalue   =   subvalue;
}

public   String   toString()   {
//   TODO   Auto-generated   method   stub
return   super.toString()   +   "   ,subvalue   : "   +   subvalue;
}

private   void   writeObject(java.io.ObjectOutputStream   oos)throws   IOException{

//先序列化对象
oos.defaultWriteObject();
//在序列化父类的域
oos.writeInt(supervalue);
}

private   void   readObject(ObjectInputStream   ois)throws   IOException,   ClassNotFoundException{

//先反序列化对象
ois.defaultReadObject();
//再反序列化父类的域
supervalue   =   ois.readInt();
}
}


测试程序:

package   InherSerialTest2;

import   java.io.FileInputStream;
import   java.io.FileOutputStream;
import   java.io.ObjectInputStream;
import   java.io.ObjectOutputStream;

public   class   InherSerialTest2   {

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   {
//   TODO   Auto-generated   method   stub

SubC   sub   =   new   SubC(100,   500);

try{
ObjectOutputStream   oos   =   new   ObjectOutputStream(
new   FileOutputStream( "c:\\InherSerialTest2.txt "));
oos.writeObject(sub);
oos.close();