英文:
How to read serialized data when serialVersionUID don't match?
问题
我在一个ArrayList中有数据,写入到一个流中:
public class CustomHoliday implements Serializable {
String name;
int day;
int month;
}
ArrayList<CustomHoliday> allCustomHolidays;
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(allCustomHolidays);
当我尝试用以下代码读取:
FileInputStream fileInputStream = context.openFileInput(filename);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
allCustomHolidays = (ArrayList<CustomHoliday>) objectInputStream.readObject();
我得到了这个异常:
java.io.InvalidClassException: CustomHoliday; local class incompatible: stream classdesc serialVersionUID = -8822681925170234017, local class serialVersionUID = -8039319578138251384
是的,我知道我应该在CustomHoliday中声明一个serialVersionUID
。但现在为时已晚。我尝试将serialVersionUID
设置为异常中的值,但那只在该设备上起作用。在其他情况下,保存的serialVersionUID
似乎是不同的。
即使我可以预先从流中读取serialVersionUID
,由于serialVersionUID
是final
的,我也无法在CustomHoliday中动态设置它。
有没有办法告诉Java:“不要担心serialVersionUID,一切都会没问题!”?
如果没有,还有其他方式可以从流中读取数据吗?对于每个CustomHoliday实例,数据只包括一个字符串和两个整数。
英文:
I have data in an ArrayList written to a stream:
public class CustomHoliday implements Serializable {
String name;
int day;
int month;
}
ArrayList<CustomHoliday> allCustomHolidays;
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(allCustomHolidays);
When I try to read that with
FileInputStream fileInputStream = context.openFileInput(filename);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
allCustomHolidays = (ArrayList<CustomHoliday>) objectInputStream.readObject();
I get this Exception:
> java.io.InvalidClassException: CustomHoliday; local class incompatible: stream classdesc serialVersionUID = -8822681925170234017, local class serialVersionUID = -8039319578138251384
Yes, I know, I should've declared a serialVersionUID
in CustomHoliday. But now it's too late for that. I've tried to set the serialVersionUID
to the one from the Exception, but that only does the trick on that device. In other instances the saved serialVersionUID
seems to be different.
Even if I could read the serialVersionUID
from the stream beforehand, I wouldn't be able to set it dynamically in CustomHoliday due to serialVersionUID
being final
.
Is there a way to tell Java: "Don't worry about the serialVersionUID, it'll be fine!"?
If not, is there another way I can read the data from the stream? It's just a String and two ints per CustomHoliday instance.
专注分享java语言的经验与见解,让所有开发者获益!
评论