0

I have one class Data.java

public class Data{
   private String name;
   private String age;
   // getters and setters for the above fields
 }

In one of my method i performed

  String newData = getData().toString();

But now i want the Data object back in its state instead of string object. so how to perform this in java.

anand
  • 1,711
  • 2
  • 24
  • 59
  • **Technically**, you **could** do it **if** the String contains all necessary data to recreate the object (e.g. if `toString()` returns something like "name=abc,age=42" you could parse it and retrieve the necessary data). Still, `toString()` is just not designed for it - don't do it. And if you do not override `toString()`, it essentially returns the hash code of the object - with that information, you can **not** recreate your object. – Andreas Fester Sep 12 '14 at 06:20

4 Answers4

5

You can't do that.

Valid one is

String newData = getData().toString();

You can't get Object back from toString()

You can use Serialization. But that is not the thing you are asking.

Also you can be smart as following. Using JSon.

@Override
public String toString() {
   return new Gson().toJson(this);
}

Now you can get Object back

String str=myClass.toString();
MyClass myClass=new Gson().fromJson(str,MyClass.class);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
3

If getData() was returning the object before it should still return the object.

DanArl
  • 1,113
  • 8
  • 10
1

No you cannot.

toString() is only intended for logging and debug purposes. It is not intended for serializing the state of an Object.

If the object in question supports serialization then go with serialization and deserialization to find out how to do this.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Ok.. so i have one method which takes string as arguments so anyhow i need to convert Data object into String and then in another object i want it back as data object... So is there any way to do it – anand Sep 12 '14 at 06:19
  • @anand either use `serialization` or `Json` to convert back and forth, refer [this](http://stackoverflow.com/questions/8887197/reliably-convert-any-object-to-string-and-then-back-again). – Ankur Singhal Sep 12 '14 at 06:23
0

You cannot get the same object back. But what you can do is, you can create a new object with the same value(s) as the original one by removing each parameter of the returned String. For that you will have to ensure that you are getting all the parameters of the object in the returned string.

Overall, a very bad idea.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104