java - 序列化Java标准类时LocalClass不兼容

标签 java serialization

我在使用生成的 SerialVersionUID 序列化自定义可序列化对象时遇到问题,因为在尝试反序列化此对象时出现 InvalidClassException 并出现以下错误:

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

我做了一个 junit 类来测试它,但这个错误不断发生。这是测试代码:

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());
   }

}

以及类(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;
}

}

我找到的有关类似问题的所有答案都是通过定义serialVersionUID来解决的,但它已经在此类中定义了 任何帮助将不胜感激!提前致谢!

最佳答案

跟着我重复一遍。 字符串不是二进制数据的容器。写出 100 次。您不应该将序列化的结果转换为字符串。然后再回来。将其作为 byte[] 数组传递。

关于java - 序列化Java标准类时LocalClass不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23385927/

相关文章:

java - Spring Security 不使用自定义 UserDetailsS​​ervice

Java HSB颜色模型: colors changing with brightness?

java - eclipse中的内存不足错误。为什么?

java - java中需要Serialized接口(interface)吗?因为接口(interface)中没有方法。它如何维护对象的状态?

.net - 使用嵌入式字典反序​​列化 JSON<string, string>

java - 我应该将序列化对象放在 Java 程序中的什么位置?

java - 将 for 循环重构为函数

python - 在 Python 中保存 KDTree 对象?

c# - 为序列化/反序列化准备 XML 数据的正确方法是什么

java - 为什么这个 Java 绘图程序不能绘制多个椭圆形?