开发者

Converting back from toString to Object

开发者 https://www.devze.com 2022-12-26 15:37 出处:网络
Is there any way to convert from toString back to the object in Java? 开发者_如何学JAVAFor example:

Is there any way to convert from toString back to the object in Java?

开发者_如何学JAVA

For example:

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

Is there any way to convert this String back to the 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.


No there isn't.

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


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 Strings 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?


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


Did you consider writing your own version to conversion utilities?

String mapToString(HashMap<String,String> map)
HashMap<String,String> stringToMap(String mapString)


public class CustomMap<K, V> extends HashMap<K, V>{
    public String toString(){
        //logic for your custom toString() implementation.
    }
}

Have a class that extends HashMap and override the toString() method. Then you can do the following and achieve what you want to,

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号