0

I need to store objects in Java as strings and then transform them back to their object form. For example, a stringified Dog class looks like this: Dog@d716361.

Any idea how can I do that or another way to store objects as strings would be appreciated.

The class:

public class Dog {
    private String name;
    
    Dog(String n) {
        name = n;
    }
    
    public String getName() {
        return name;
    }
}
Ron Caspi
  • 1
  • 1
  • 1
    That's not a stringified version of the object, that's the reference of the instance. If you need to store the objects as strings and then convert them back to objects you can use a ready-made library such as Jackson [`ObjectMapper`](https://www.baeldung.com/jackson-object-mapper-tutorial) or similar. – blurfus Nov 06 '22 at 05:45
  • Override [toString](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html) `toString() { return getName(); }`? – Neil Nov 06 '22 at 05:45
  • @blurfus That is not a reference of the instance, it is the default `toString()` implementation provided by `Object`, which prints the fully qualified class name followed by `@` and the hex encoding of the identity hashcode of the object (which could be a reference in theory, but in practice is not as Java moves objects around in memory, while the identity hashcode remains the same). – Mark Rotteveel Nov 06 '22 at 08:51
  • It was a simplified explanation for OP :) – blurfus Nov 06 '22 at 16:58

0 Answers0