Search code examples
javayamlsnakeyaml

Way to determine the type of an object and then cast an object from snake yaml.load(InputStream)


So I'm writing this utility class for all my model objects to inherit from so that whenever I call saveToFile(filename) it will save that object in a yaml format. To String just outputs the file in yaml format. What I really want to be able to do though is initialize all the attributes of an object with the attributes in a file but I don't want to have to know what type of object it is beforehand.

I want a method something along the lines of

public void loadFromFile(String filename){
    try {
        InputStream input = new FileInputStream(new File(filename));
        Yaml y = new Yaml();
        this = y.load(input);
    } catch (IOException e) {
        System.out.println(e);
    }
}

this works fine, save for the fact that you can't assign an object to "this".


Solution

  • You will have to cast:

    YourObject object = (YourObject) y.load(input);
    

    Also, don't do assignments to this. Instead you should load the object externally and use something like BeanUtils.copyProperties(object, yamlObject)

    Also take a look at the yamlbeans.

    Btw, in order to make a utility method, your cast won't work like that. You'd better pass a Class<T> argument to the method, and let it have return type T. The use clazz.cast(..) to do the cast.