Take the 2-minute tour ×

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.

share|improve this question

closed as not a real question by Jarrod Roberson, Tom G, Mark, Mike, Andrew Barber Jun 24 '13 at 16:54


(1) No one codes for free. (2)toString is meant for human readable equivalent of the object. (3) what you are looking for is Serialization and De-serialization. –  Nishant Mar 23 '11 at 6:13

9 Answers 9

up vote 10 down vote accepted


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:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() 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:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

share|improve this answer
share|improve this answer
not downvoting, but seems like OP wants to save object (with states) as String and then convert back to the object with same states. forName loads the class and gives you Class object not the instance of the class. download.oracle.com/javase/6/docs/api/java/lang/… –  Nishant Mar 23 '11 at 6:26
@Nishant - that is your interpretation of what he wants. –  Stephen C Mar 23 '11 at 6:35
sorry, my mistake; i misread class object to mean an instanced class object, not a (C)lass object. –  TurtleToes Mar 24 '11 at 5:31


First, if I'm understanding your question, you want to store your object into a String and then later to be able to read it again and re-create the Object.

Personally, when I need to do that I use ObjectOutputStream. However, there is a mandatory condition. The object you want to convert to a String and then back to an Object must be a Serializable object, and also all its attributes.

Let's Consider ReadWriteObject, the object to manipulate and ReadWriteTest the manipulator.

Here is how I would do it:

public class ReadWriteObject implements Serializable {

    /** Serial Version UID */
    private static final long serialVersionUID = 8008750006656191706L;

    private int age;
    private String firstName;
    private String lastName;

     * @param age
     * @param firstName
     * @param lastName
    public ReadWriteObject(int age, String firstName, String lastName) {
        this.age = age;
        this.firstName = firstName;
        this.lastName = lastName;

     * (non-Javadoc)
     * @see java.lang.Object#toString()
    public String toString() {
        return "ReadWriteObject [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";


public class ReadWriteTest {

        // Create Object to write and then to read
        // This object must be Serializable, and all its subobjects as well
        ReadWriteObject inputObject = new ReadWriteObject(18, "John", "Doe");

        // Read Write Object test

        // Write Object into a Byte Array
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        byte[] rawData = baos.toByteArray();
        String rawString = new String(rawData);

        // Read Object from the Byte Array
        byte[] byteArrayFromString = rawString.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayFromString);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object outputObject = ois.readObject();

The Standard Output is similar to that (actually, I can't copy/paste it) :

¬í ?sr ?*com.ajoumady.stackoverflow.ReadWriteObjecto$Ë²é¦LÚ ?I ?ageL ?firstNamet ?Ljava/lang/String;L ?lastNameq ~ ?xp ?t ?John ?Doe

ReadWriteObject [age=18, firstName=John, lastName=Doe]

share|improve this answer

As stated by others, your question is ambiguous at best. The problem is, you want to represent the object as a string, and then be able to construct the object again from that string.

However, note that while many object types in Java have string representations, this does not guarantee that an object can be constructed from its string representation.

To quote this source,


So, you see, what you want might not be possible. But it is possible to save your object's state to a byte sequence, and then reconstruct it from that byte sequence.

share|improve this answer

You might want to do it with json.
Convert your bean(*) to json an then back.
this proccess is known as serialisation and deserialisation
read about it here http://www.json.org/javadoc/org/json/JSONObject.html

(*) Dont use just members as the data source, build getters and setters for each member in your object.

share|improve this answer

Continuing from my comment. toString is not the solution. Some good soul has written whole code for serialization and deserialization of an object in Java. See here: http://www.javabeginner.com/uncategorized/java-serialization

Suggested read:

  1. Old and good Java Technical Article on Serialization
  2. http://java.sun.com/developer/technicalArticles/ALT/serialization/
  3. http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/serial.html
share|improve this answer

You cannot store a class object into a string using toString(), toString() only returns a String representation of your object-in any way you'd like. You might want to do some reading about Serialization.

share|improve this answer

You can use the statement :-

Class c = s.getClass();

To get the class instance.

share|improve this answer

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

share|improve this answer
