假設已知對象的確切類別,什麼是將任意對象轉換爲字符串表示或從其轉換字符串表達式的常用方法?換句話說,我需要實現類似於以下一些方法:接受的練習用於將對象轉換爲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的協議緩衝區),並且我可以輕鬆地自行實施一次性解決方案。我的問題不是「我該如何解決這個問題」,而是「現有的許多現成解決方案中的哪一個是當前的行業標準?」。