• Post Reply Bookmark Topic Watch Topic
  • New Topic

Objects from a String representation of an object  RSS feed

 
Siva Kannan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Friends,

Is there any to convert an string representation of an object to object?

For example, I have a class called TestObject and while storing it into a flat file using dataoutputstream, I am storing it as TestObject.toString(). So when i read it back I want to convert the String into a TestObject? Is this possible. Please advice.

PS: I knew you can store the object itself using objectoutputstream. I just want to know if this possible or not.

THanks
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure it can be done. You need to convert all the elements of your objects to Strings and combine all those Strings into one big String. Of course you must also add to the String how to identify the individual pieces so you can reconstruct your object. This is called metadata - data about your data. And the standard protocol for that is XML.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few ways to do this. All of them require you to parse the String back into its components, then construct an object from that. The easiest way is to add a constructor that takes a String. Or, if this isn't possible because you already have such a constructor, add a static factory method:
As to what XXX is, you have a few options. IllegalArgument and ParseException are the most logical choices.

The parsing can use regular expressions for validation, perhaps using a Scanner.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!