Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Oct 2008
    Messaggi
    2

    Very strange problem with enum serialization

    I've this class hierarchy

    codice:
    //file Type.java
    
    public enum Type{
    
     TypeA,TypeB;
    
    }
    codice:
    //File Message.java
    
    public abstract class Message {
    
      private Type type;
    
     //getter and setter methods
    
    }
    
    //File MessageImpl.java
    
    public class MessageImpl extends Message {
    
      private int x;
    
     //getter and setter methods
    
    }
    Now if i try to serialize and deserialize (with ObjectOutputStream and ObjectInputStream open on a socket) a MessageImpl object, i will obtain a MessageImpl instance

    with the same 'x' value but with a null value for type field also if i've specified one.

    The strange thing is that if i use this class:

    codice:
    //File MessageImpl2.java
    
    public class MessageImpl2.java{
    
      private Type type;
    
      private int x;
    
     //getter and setter methods
    
    }
    the serialization of a MessageImpl2 object works well.

    Do you kwow how class hierarchy can affect enum serialization???

    Thanks

  2. #2
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,328
    You must implement Serializable interface in the Message class if you want to serialize such type of objects.

    codice:
    public abstract class Message implements Serializable {
       ...
    }
    So, you ensure all your sub-classes to be serializable.


    PS: Use the CODE tag when you post code snipplets.

    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  3. #3

    Re: Very strange problem with enum serialization

    Originariamente inviato da fra86co
    //File Message.java

    public abstract class Message {

    private Type type;

    //getter and setter methods

    }

    //File MessageImpl.java

    public class MessageImpl extends Message {

    private int x;

    //getter and setter methods

    }
    Hi...

    Are you sure Message class is correctly inherited by MessageImpl?
    You should declare type as public or protected to make it inheritable.
    lolide
    Java Programmer

    Informati

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.