سؤال

I'm having problems to serialize a custom serializable object with a generated SerialVersionUID, since i get an InvalidClassException when trying to deserialize this objetc with the following error:

< com.assistantindustries.test.Prueba; local class incompatible: stream classdesc serialVersionUID = 6090585534595974753, local class serialVersionUID = 6090585536173033057>

I made a junit class for testing it and this error keeps happening. Here's the code for the test:

public class TestSerializacion {

   public String pruebaToString(Serializable prueba){
       ByteArrayOutputStream bs= new ByteArrayOutputStream();
       ObjectOutputStream os = null;
    try {
        os = new ObjectOutputStream (bs);
        os.writeObject(prueba);
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
       return bs.toString();
   }

   public static Prueba getPruebaFromString(String prueba){
       ByteArrayInputStream bs= new ByteArrayInputStream(prueba.getBytes());
       ObjectInputStream is = null;
       Prueba unObjetoSerializable = null;
    try {
        is = new ObjectInputStream(bs);
        unObjetoSerializable = (Prueba)is.readObject();
        is.close();
    } catch (ClassNotFoundException | IOException e1) {
        e1.printStackTrace();
    }
       return unObjetoSerializable;
   }

   @Test
   public void testBasico(){
       int i=453;
       Prueba prueba=new Prueba(i);
       String toSend=pruebaToString(prueba);
       Prueba recibida=getPruebaFromString(toSend);
       assertEquals(prueba.getPhrase(),recibida.getPhrase());
   }

}

And the Class:

public class Prueba implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 6090585536173033057L;
ArrayList<String> texts;

public Prueba(int semilla) {
    Random r=new Random(semilla);
    this.texts = new ArrayList<String>();
    for (int i = 0; i < 100; i++) {
        char[] palabra=new char[10];
        for (int j = 0; j < palabra.length; j++) {
           palabra[j]=(char) (r.nextInt(256));
        }
        texts.add(new String(palabra));
    }
}

public synchronized ArrayList<String> getTexts() {
    return texts;
}

public synchronized void setTexts(ArrayList<String> texts) {
    this.texts = texts;
}

public String getPhrase(){
    String total="";
    for(String s:this.texts){
        total.concat(s);
    }
    return total;
}

}

All the answers I found about similar problems were solved by defining the serialVersionUID, but it is already defined in this class Any help would be greatly appreciated! Thanks in advance!

هل كانت مفيدة؟

المحلول

Repeat after me. String is not a container for binary data. Write out 100 times. You shouldn't convert the result of serialization to a String. and back again. Pass it around as a byte[] array.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top