Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object fromString method?

Tags:

java

json

gson

So I realize there is a toString() method from the Object class. However how do I set a fromString() method?

public String toString() {
    return "";
}

What's the point of having toString() and not fromString()? Or am I just not able to find it? To clarify I am trying to use Gson and it keeps converting my object to its string representation instead of as the object.

like image 330
ThatGuy343 Avatar asked Feb 09 '23 07:02

ThatGuy343


2 Answers

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.

like image 88
pb2q Avatar answered Feb 11 '23 19:02

pb2q


It would be hard to implement. It seems logical that fromString(object.toString()) should reconstruct the object. Then, the toString() then would have to have all information needed to initialize that class, instead of just the important stuff.

For example, consider an ArrayList. Its toString() gives only its contents, which seems fine and useful until your try to initialize it…you'd need to properly set its capacity, for example, but you don't have access to it from its toString(). But you wouldn't want to see that in its toString() for encapsulation reasons.

like image 22
saagarjha Avatar answered Feb 11 '23 19:02

saagarjha