Note the following from the documentation for toString
:
The result should be a concise but informative representation that is easy for a person to read.
This method is less than functional: it's used to present human-readable information, useful i.e. for debugging.
A more purpose-driven API, which seems to be what you're suggesting, will be pretty context-specific. Often you'll see something similar to a fromString
, see for instance the various parse
methods.
The closest that we have to a general approach is the object serialization and de-serialization API (tutorial here, docs here), which is still left open for specific implementation:
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
None of this precludes you from writing your own fromString
, but it sounds like you're having a specific problem with the Gson libraries. Look at the various fromJson
overloads, starting here.