Search code examples
javayamlsnakeyaml

snakeYaml refer to the same instance of an object multiple times


Inside of a list, I would like to refer to the same instance object multiple times:

- text: Here is an object with some data that will allow an image to be generated
  image: &FirstIm
      imageType: ABC
      otherTypE: CB
- text: Later on, lets show you the same image again!
  image: *FirstIm

What I'm doing is generating an image using the properties provided and caching it in the image object. Because of the specific implementation, I cannot generate the image again, so I would like to refer back to specific instances of an image object.

Unfortunately, snakeYAML treats the above as "oh, so you'd like another object, but with the same properties as FirstIm" so when I check the second image objects cache, there's nothing in it. The behaviour I need is "you want FirstIm again, ok, ill put that there".

Is there any way of achieving this without using some kind of string in the image object to refer to some higher level caching?

Hope this makes sense...


Solution

  • I think there are some issues in your code or I still do not understand the question, because yaml from your question passes test just fine.

    Cannot put code in the comment. So here it is.

    import java.util.List
    import java.util.Map
    ...
    Yaml yaml = new Yaml();
    List load = yaml.loadAs("- text: Here is an object with some data that will allow an image to be generated\n  image: &FirstIm\n    imageType: ABC\n    otherTypE: CB\n- text: Later on, lets show you the same image again!\n  image: *FirstIm", List.class);
    assertSame(((Map)load.get(0)).get("image"), ((Map)load.get(1)).get("image"));