On 5/19/2014 4:01 PM, Philipp Kraus wrote:
I have got a non-serializable class and I would like to store / load
these objects. So my idea
is creating a encapsulate the class:
class myClass implements Serializable
{
add some properties
public myClass( myNonSerializableInterface data )
{
add members from data to properties
}
public myNonSerializableInterface create()
{
return ??
}
}
My problem is, that I don't know in which way I can restore the
interface object?
So I need to store the object name. Can anybody help me to create a working
serializable structure? I'm a little bit confused at the moment to solve
the problem
Ted Neward once came up with a pattern Serializable Adapter to solve
that problem.
Here is an example of how it can be done (I am the author of the
example so give Ted Neward credit for the idea and blame me for
bugs in implementation).
We have a data class that are not serializable:
public class Data {
private int iv;
private String sv;
public int getIv() {
return iv;
}
public void setIv(int iv) {
this.iv = iv;
}
public String getSv() {
return sv;
}
public void setSv(String sv) {
this.sv = sv;
}
public String toString() {
return ("[" + iv + ":" + sv + "]");
}
}
We have a little piece of convenience code:
import java.io.Serializable;
public class SerializableAdapter implements Serializable {
protected transient Object object;
public Object getObject() {
return object;
}
}
And now we create the specific adapter class:
public class DataSerializable extends SerializableAdapter {
public DataSerializable(Data o) {
object = o;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeInt(((Data)object).getIv());
oos.writeUTF(((Data)object).getSv());
}
private void readObject(ObjectInputStream ois) throws IOException,
ClassNotFoundException {
object = new Data();
((Data)object).setIv(ois.readInt());
((Data)object).setSv(ois.readUTF());
}
}
Which is perfectly serializable and deserializable.
Arne