Is there any way to convert from toString back to the object in Java?
For example:
Map myMap = new HashMap
No there isn't.
toString() is only intended for logging and debug purposes. It is not intended for serialising the stat of an Object.
A string is also an object. And no it's not possible to get the original object from its string representation (via toString()
). You can simply get this by thinking about how much information is (or can be) stored within an object but how short the string representation is.
imposible if you think you can 'cast' the string; try parsing; something like:
public static Map<String,String> parseMap(String text) {
Map<String,String> map = new LinkedHashMap<String,String>();
for(String keyValue: text.split(", ")) {
String[] parts = keyValue.split("=", 2);
map.put(parts[0], parts[1]);
}
return map;
}
Short answer: no.
Slightly longer answer: not using toString
. If the object in question supports serialization then you can go from the serialized string back to the in-memory object, but that's a whole 'nother ball of wax. Learn about serialization and deserialization to find out how to do this.
Nope. Beside parsing this string returned by myMap.toString()
and puting parsed values back into the map. Which doesn't seem to complicated here, since you have only String
s in your Map
, so the output of myMap.toString()
should be quite readable/parseable.
But in general this is not a great idea. Why to you want to do that?
Did you consider writing your own version to conversion utilities?
String mapToString(HashMap<String,String> map)
HashMap<String,String> stringToMap(String mapString)