I am storing a class object into a string using toString()
method. Now, I want to convert the string into that class object.
How to do that? Please help me with source code.
I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.
Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.
If you did this:
SomeClass object = ... String s = object.toString();
then the answer is that there is no simple way to turn s
back into an instance of SomeClass
. You couldn't do it even if the toString()
method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)
The only way you could turn the output of toString
back into an object would be to:
SomeClass.toString()
method so that included all relevant state for the object in the String it produced, andtoString()
method.This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.
If you did something like this:
SomeClass object = ... Class c = object.getClass(); String cn = c.toString();
then you could get the same Class
object back (i.e. the one that is in c
) as follows:
Class c2 = Class.forName(cn);
This gives you the Class
but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)
If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString()
method at all. Here are some alternatives that you can use:
Each of these approaches has advantages and disadvantages ... which I won't go into here.
Much easier way of doing it: you will need com.google.gson.Gson for converting the object to json string for streaming
to convert object to json string for streaming use below code
Gson gson = new Gson(); String jsonString = gson.toJson(MyObject);
To convert back the json string to object use below code:
Gson gson = new Gson(); MyObject = gson.fromJson(decodedString , MyObjectClass.class);
Much easier way to convert object for streaming and read on the other side. Hope this helps. - Vishesh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With