samedi 24 février 2018

SnakeYaml not using my setters

I am trying to parse a YAML file with SnakeYaml in Java and I am struggling to make it build my model objects via the setters. What I understood from the SnakeYaml doc, is that when you use object that follow the JavaBean rules, SnakeYaml uses reflection to find setters and use them to instanciate members.

I shrunk down the code to the following minimalist version, and it still does not work as I would expect:

This is my model object :

public class Report {

    private String MainSourceFile;

    public Report() {
        super();
    }

    public String getMainSourceFile() {
        return this.MainSourceFile;
    }

    public void setMainSourceFile(String mainSourceFile) {
        this.MainSourceFile = mainSourceFile;
    }
}

This is the code that parses the YAML file :

Constructor constructor = new Constructor(Report.class);

Yaml yaml = new Yaml(constructor);
Report report = null;

try (InputStream str = new FileInputStream(file);) {
    report = (Report) yaml.load(str);
} catch (FileNotFoundException e) {
    throw new ParsingErrorException( String.format("Error while reading export file %s : file not found", file.getAbsolutePath()), e);
} catch (YAMLException e) {
    throw new ParsingErrorException(String.format("Error while parsing export file %s", file.getAbsolutePath()), e);
} catch (IOException e1) {
    Activator.logWarning(String.format("Error while closing file %s", file.getAbsolutePath()));
}

And this is the YAML file :

---
MainSourceFile:  /home/user/workspace/project/ex.c

If I declare the MainSourceFile member as public, the parsing works (that's why it begins with an upper case). But I'd prefer not to let it public and furthermore, I would like to use the setter. I don't understand the reason why it does not use the setter : my Report class seems a legit JavaBean to me.

Is there anything else that I am missing?





Aucun commentaire:

Enregistrer un commentaire