Since you are saving the information, you can also print out the type.
For example, you can use something like:
for (final Animals animal : myAnimalList){
output.print(animal.getClass().getSimpleName());
output.println(animal.getData());
}
For instances of Dog
, this will print out "Dog"
and for instances of Cat
, it will print out "Cat"
. Followed by the getData()
information. This is assuming that getData()
would contain the appropriate data for printing out the information.
Then you can achieve something like:
Dog[name=Ruff, age=17, favoriteToy=Ball]
Cat[name=Tom, age=102, hates=Everyone]
Then, you can easily fill in the information required to reconstruct dogs and cats, based off of the required fields.
That being said, you can then write this out to the file. This is, as suggested in your question, similar to the way you are already doing this.
This has already been done before, so creating your own methods and all that is not recommended.
The alternative is to have a unique identifier for each class (think serialVersionUID
).
This is just a form of Serialization. Having basic read
and write
methods can then handle parsing the correct data on a class-to-class basis.
It would be far better to implement Serializable
for the Animals
class, then sent fields you don't want to be written and read to transient
.
Then, you can just fill all the appropriate methods with these signatures:
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
private void readObjectNoData() throws ObjectStreamException;