Converting back from toString to Object

前端 未结 7 1711
谎友^
谎友^ 2020-12-11 21:23

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

For example:

Map myMap = new HashMap

        
相关标签:
7条回答
  • 2020-12-11 22:14
    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 讨论(0)
提交回复
热议问题