我在使用生成的 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/