arm*_*adi 2 java serialization arraylist subclass extend
我想序列化Item的arraylist 但它不起作用....
我的Item类扩展了Stuff类并且有一些子类.
我的所有类都实现了Serilalizable.
我有这个部分:
Run Code Online (Sandbox Code Playgroud)try{ // Serialize data object to a file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser")); out.writeObject(myData); out.close(); // Serialize data object to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(myData); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { }我的课程 :
Run Code Online (Sandbox Code Playgroud)public class Stuff implements Serializeable{ .... some protected fields . . } public class Item extends Stuff implements Serializable{ ... .. . } and some subclasses of Item: public class FirstItem extends Item implements Serializable{ ... } public class SecondItem extends Item implements Serializable{ ... } ... I want to serialize an object contains ArrayList of <Item> that has objects of Item's subclasses (FirstItem,SecondItem,...)我认为信息就足够了......
这只是一个小错误,现在工作正常......我很抱歉我的愚蠢问题.
谢谢您的回答.
您可以像这样序列化ArrayList类
public class MyData implements Serializable {
private long id;
private String title;
private ArrayList<String> tags;
...
public String getTitle() {
}
}
Run Code Online (Sandbox Code Playgroud)
并创建可序列化
ArrayList<MyData> myData = new ArrayList<MyData>();
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
out.writeObject(myData);
out.close();
// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(myData);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20754 次 |
| 最近记录: |