我有一个类save() and load()
void save() { ... }
static final Foo load() { ... }
,其中包含以下两种方法:
class Foo {
String field1;
int field2;
}
new way:
class Foo {
class Bar {
String field1;
int field2;
}
Bar data;
void load() { data = deserlializeBar(); }
}
这些方法的目的是通过Java Serialization
保存和加载Foo对象然而,我现在已经意识到它们根本无法满足我的需要 - 即因为为了加载数据,我必须创建一个Foo类的品牌打击新对象。
我需要做的是有时从Foo中调用load ...以便能够直接反序列化到现有的Foo对象中(替换现有的数据)
我该怎么做?
我能想到的是将Foo中存在的所有字段移动到内部类
salida = fopen(final, "r");
有没有更简单的方法?
答案 0 :(得分:0)
问题非常简单 - 如何通过序列化将数据加载到现有对象
您是如何访问现有对象的?如果您有访问现有对象的map
,则可以通过以下方式重新加载数据:
让所有对象都成为唯一ID。如果要从反序列化数据刷新数据,请从反序列化对象重新填充现有对象的所有字段。这是一个例子:
public class RelaodFromDeSerialidedData
{
HashMap<Integer, Foo> inMemoryObjects = new HashMap<Integer, Foo>();
public void loadData()
{
for (Foo deSerializedFoo : getDeSerializedFoo())
{
if (inMemoryObjects.containsKey(deSerializedFoo.id))
{
// now reload the fileld(s) you want from deSerialized object
Foo inMemoryFoo = inMemoryObjects.get(deSerializedFoo.id);
inMemoryFoo.name = deSerializedFoo.name;
// .....
inMemoryObjects.remove(deSerializedFoo.id);
inMemoryObjects.put(deSerializedFoo.id, inMemoryFoo);
}
}
}
public static ArrayList<Foo> getDeSerializedFoo()
{
ArrayList<Foo> f = new ArrayList<Foo>();// logic to deserialize and return foo object List
return f;
}
}
class Foo
{
int id;
String name;
String otherData;
}
答案 1 :(得分:0)
它是重复的 Deserialize JSON into existing object (Java)
使用以下代码:
ObjectMapper mapper = new ObjectMapper();
mapper.readerForUpdating(object).readValue(json);
答案 2 :(得分:-1)
让你的Foo类实现Serializable,然后你可以使用ObjectOutputStream将你的对象写入磁盘。