假设已知对象的确切类别,什么是将任意对象转换为字符串表示或从其转换字符串表达式的常用方法?换句话说,我需要实现类似于以下一些方法:接受的练习用于将对象转换为Java中的字符串和从中转换为字符串?
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);
}
理想情况下,解决方案应:
- 如果可能的话使用对象的内置的toString()功能。因此,converter.asString(new Integer(5))应该返回“5”,并且converter.asObject(“5”,Integer.class)应该返回值为5的Integer。
- 生成输出,尽可能可读。
- 处理所有常见的Java数据类型,包括java.util.Date。
- 允许我为自己的自定义类插入转换功能。
- 合理轻量且高效。
我知道有很多现成的解决方案可以做到这一点(比如Google的协议缓冲区),并且我可以轻松地自行实施一次性解决方案。我的问题不是“我该如何解决这个问题”,而是“现有的许多现成解决方案中的哪一个是当前的行业标准?”。