What is the commonly accepted method for converting arbitrary objects to and from their String representations, assuming that the exact class of the object is known ? In other words, I need to implement some methods similar to the following:
public interface Converter {
/**
* Convert this object to its String representation.
*/
public String asString(Object obj);
/**
* Take the String representation of an object produced by asString,
* and convert it back to an object of the appropriate class.
*/
public Object asObject(String stringRepresentation, Class clazz);
}
Ideally, the solution should:
- Use the object's built-in toString() functionality, if possible. Thus, converter.asString(new Integer(5)) should return "5", and converter.asObject("5", Integer.class) should return an Integer with the value of 5.
- Produce output that is human-readable whenever possible.
- Deal with all common Java data types, including java.util.Date .
- Allow me to plug in conversion functionality for my own, custom classes.
- Be reasonably light-weight and efficient.
I understand that there are any number of ready-made solutions that do this (such as Google's protocol buffers, for example), and that I could easily implement a one-off solution myself. My question is not, "how do I solve this problem", but rather, "which one of the many ready-made solutions is the current industry standard ?".