今天学习写个即时通信工具,遇到了对象序列化对继承影响的问题。
定义了消息对象:
class Message
{
protected byte type;
public byte getType(){
return this.type;
}
}
class LoginMessage extends Message implements Serializable
{
public LoginMessage(){
this.type=1;
}
}
客户端的代码:
public class ClientTest {
public static void main(String[] args){
try{
Socket s=new Socket("localhost",9000);
OutputStream os=s.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(new LoginMessage());
}
catch(IOException e){
e.printStackTrace();
}
}
}
服务器端的代码:
public class ServerTest {
public static void main(String[] args){
try{
ServerSocket s=new ServerSocket(9000);
Socket incoming=s.accept();
ObjectInputStream in=new ObjectInputStream(incoming.getInputStream());
System.out.println(((Message)in.readObject()).getType());
in.close();
}catch(IOException e){
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
结果程序输出0,而不是1.
分析:因为父类没有实现序列化,导致其子类序列化时继承自父类的属性不能被保存。在Java doc中明确指出,如果一个类继承了一个非Serializable类时,如果想在序列化中保存父类的属性,则需要实现额外的代码显式地存储父类的属性值。
在自己的代码中,可以将父类实现序列化,子类将自动实现序列化。