Convert back from toString to Object

Is there a way to convert from toString back to a Java object?

For instance:

Map<String, String> myMap = new HashMap<String, String>(); myMap.put("value1", "test1"); myMap.put("value2", "test2"); String str = myMap.toString(); 

Is there a way to convert this string to Map?

+4
source share
7 answers

The short answer is no.

Slightly long answer: do not use toString . If the object in question supports serialization, then you can go from the serialized string back to the object in memory, but this is a solid "wax ball". Learn about serialization and deserialization to find out how.

+7
source

Not. Not.

toString () is for logging and debugging only. It is not intended to serialize a stat object.

+1
source

Nope. In addition to parsing this string returned by myMap.toString() , and reprocessing the parsed values โ€‹โ€‹on the map. This doesn't seem complicated here, since your Map only has String , so the output of myMap.toString() should be completely readable / processable.

But overall this is not a great idea. Why do you need this?

0
source

The string is also an object. And there is no way to get the source object from its string representation (via toString() ). You can simply get this by thinking about how much information (or maybe) is stored inside the object, but how short the string representation is.

0
source

impossible if you think you can overlay a string; try to make out; sort of:

 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; } 
0
source

Have you considered your own version for conversions?

 String mapToString(HashMap<String,String> map) HashMap<String,String> stringToMap(String mapString) 
0
source
 public class CustomMap<K, V> extends HashMap<K, V>{ public String toString(){ //logic for your custom toString() implementation. } } 

You have a class that extends HashMap and overrides the toString () method. Then you can do the following and achieve what you want,

  CustomMap<String, String> myMap = new CustomMap<String, String>(); myMap.put("value1", "test1"); myMap.put("value2", "test2"); String str = myMap.toString(); 
0
source

Source: https://habr.com/ru/post/1306302/


All Articles