ObjectInputStream read a empty object

2019-07-18 19:10发布

I wrote a object using ObjectOutputStream, and read it using ObjectInputStream, and tested it , I get the expected result. But when write the object in other machine, read it in my computer, the read object's members are empty. Could someone help me? thanks

   public class TrustNet implements Serializable{

     public double[][] trusts;
     public double avg = 0;

     public TrustNet(int size){
        trusts = new double[size][size];
     }

    public void writeToFile(String fileName){
        try(ObjectOutputStream writer = new ObjectOutputStream(new  FileOutputStream(fileName))){
        writer.writeObject(this);
        writer.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    }

   public static TrustNet readFromFile(String fileName){
    try(ObjectInputStream writer = new ObjectInputStream(new FileInputStream(fileName))){
        return (TrustNet) writer.readObject();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    return null;
   }

  }

1条回答
欢心
2楼-- · 2019-07-18 20:03

It took me a day to figure out what's going on. I think I finally have the answer. May be it will help other people having similar problem.

In my case, the problem was due of using ProGuard.

  1. ProGuard minifyed the code, giving new shorts names to fields, like a, b, c, etc.
  2. When serializing, the names of fields get stored into the stream. When reading the stream, the names must match.
  3. When I minifyed code the last time (for the new Production version of the app), ProGuard gave different names to fields (in my case it was due of changed ProGuard settings, but may be due of other reasons too, not sure if ProGuard guarantee the same names every time).
  4. As result, when I deserialize the object in the new version, because of the names are not match, all the fields set to default values.
查看更多
登录 后发表回答