1

Here is the minimum full code I tried :

import java.util.Map;

import org.testng.Assert;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;

import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;

public class LoadObservable {

    public static class MapStorage {

        private ObservableMap<String, String> map = FXCollections.observableHashMap();

        public void setMap(Map<String, String> newmap) {
            map.clear();
            map.putAll(newmap);
        }

        /**
         * fails
         */
        public ObservableMap<String, String> getMap() {
            return map;
        }

        /**
         * pass
         */
        public Map<String, String> getMap() {
            return map;
        }
    }

    @Test
    public void load() {
        MapStorage storage = new MapStorage();
        storage.map.put("nice", "dog");
        String dumped = new Yaml().dump(storage);
        MapStorage loaded = new Yaml().loadAs(dumped, MapStorage.class);
        Assert.assertEquals(loaded.map.get("nice"), "dog", "dumped is " + dumped);
    }


}

At first I tried with only a public field, but then snakeyaml writes it as a LinkedHashMap and can't cast it to an ObservableMap. Then I remembered snakeyaml uses getters/setters and tried to used them.


The code that pass presents the ObservableMap as a Map in the getter, and uses a Map in the setters to set the values of the ObservableMap. However since it does not present the ObservableMap to the user, it is useless to keep an observableMap. I sure could add another getter that returns the real type, however since I have tens of fields in my real cases this would be very bad for the user.

What I would like to, is to use the code that at the moment fails. Any idea ?

guigolum
  • 131
  • 1
  • 7
  • +1 for adding a minimal example. But next time try to prevent the use of external libraries that are not part of the problem. In this case it's `org.testng`. Maybe replace the `load()` method with a normal main method so that you don't need to import the `org.tesng` packages. That way it is easier for everyone to run your code. – Markus Köbele Feb 15 '18 at 12:28
  • I don't use `snakeyaml` myself but [this answer](https://stackoverflow.com/a/28552015/4240433) looks like it could be a starting point for your problem. – Markus Köbele Feb 15 '18 at 12:43
  • @MarkusK This is totally unrelated. Next time I will use the same libs, sorry but you can replace testng by JUnit or whatever. – guigolum Feb 15 '18 at 13:34

0 Answers0