Reputation: 1338
Hi I am trying to deserialize the following object.
public class Book extends Item implements Serializable {
public Boolean isBook;
public Boolean isBookch;
private String publicationPlace;
private String publisher;
private int edition;
private String pages;
private String article;
Book(String title, String author, String year)
{
super(title, author, year);
isBook = false;
isBookch = false;
publicationPlace = " !!! Not Known !!! ";
publisher = " !!! Not Known !!! ";
edition = 1;
pages = "!!! Not Known !!!";
article = " !!! Not Known !!! ";
}
this is structure of the object and I am serailizing it as ....
openw("books.dat");
Date date = new Date ();
out.writeObject(date);
for(Book b : books )
out.writeObject ( b );
closew();
and this is working pretty much working fine with out any errors. I am tryin to decentralize it as ...
openr("books.dat");
Date lastsaved = (Date)in.readObject();
System.out.println("last saved date : " + lastsaved.toString());
while( true )
{
Object o = in.readObject();
if(o == null )
break;
else
{
addItem((Book)o);
books.add((Book)o);
}
}
closer();
and this is giving the error as : java.io.InvalidClassException: Book; no valid constructor
How to clear this problem.. thanx in advance...
Upvotes: 4
Views: 879
Reputation: 27803
The class Item
must implement Serializable
as well,
class Item implements Serializable {
// ...
}
and it works!
If however, Item
is out of your reach and does not have a non-argument constructor, you cannot make Book
serializable. The only way to make a subclass of a non-serializable class serializable is if a "subclass-accessible no-arg constructor of first non-serializable superclass" is found (quoting from the source code of ObjectStreamClass
's getSerializableConstructor
method). Which in your case seems to be missing, so Book
cannot be made serializable.
In which case, given your object consists of primitives only anyway, you could to look into JSON as an alternative way of serializing objects. There’s a list of JSON libraries for Java on http://www.json.org
NB, how is it possible that Java can create objects of serializable classes without calling a constructor? There’s an unsafe method somewhere deep down in Java's API that is used to allocate objects without calling their constructor. True story.
Upvotes: 2