简体   繁体   English

最佳实践来更新我的数据结构?

[英]Best practice to update my data structure?

I have the following problem and need a best practice to solve it: 我有以下问题,需要最佳实践来解决:

I have a App with a List of data of Type Foo . 我有一个带有Foo类型数据列表的应用程序。 This list ( ArrayList<Foo> ) I save to the file system with: 我使用以下命令将该列表( ArrayList<Foo> )保存到文件系统:

FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(MyList);
oos.close();

When I start the App I load it with: 启动应用程序时,我将其加载:

FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
MyList = (ArrayList<Foo>) ois.readObject();
ois.close();

Now my problem: I want to extend the Foo class with some additional attributes. 现在我的问题是:我想用一些附加属性扩展Foo类。 The problem is, that a user has the old list saved and want to load it into the new Foo class, the app will crash. 问题是,用户保存了旧列表并想将其加载到新的Foo类中,该应用将崩溃。

What is aa best practice to solve this update problem? 解决此更新问题的最佳实践是什么?

Using Serialization in your scenario may not be the best pick. 在您的方案中使用序列化可能不是最佳选择。 To avoid the crash you can use serialVersionUID to distinguish betweeen different versions of the same class. 为避免崩溃,您可以使用serialVersionUID区分同一类的不同版本。

From the Java API: 通过Java API:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. 序列化运行时与每个可序列化的类关联一个版本号,称为serialVersionUID,在反序列化期间使用该版本号来验证序列化对象的发送者和接收者是否已加载了该对象的与序列化兼容的类。

If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. 如果接收方已为该对象加载了一个与相应发送方类具有不同的serialVersionUID的类,则反序列化将导致InvalidClassException。

A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long. 可序列化的类可以通过声明一个名为serialVersionUID的字段来显式声明其自己的serialVersionUID,该字段必须是静态的,最终的且类型为long。

Is your data model so complex that it can't be written in SQLite DB? 您的数据模型是否如此复杂,以致无法在SQLite DB中编写? This will allow you to handle the load of the model selectively, skipping null attributes that may result loading a new model with an older structure. 这将允许您有选择地处理模型的加载,跳过可能导致加载具有旧结构的新模型的空属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM