How to use static method to construct in snakeyaml?

549 views Asked by At

I have a class with a private constructor and a static method that returns instances, like below:

public class OptionsBean {
    public static final OPTION1 = new OptionsBean(0, "COLOR");
    public static final OPTION2 = new OptionsBean(1, "SIZE");

    private OptionsBean(int id, String name) { ... }

    public static OptionsBean valueOf(String name) {
        if (name.equals("COLOR")) {
            return OPTION1;
        } else {
            return OPTION2;
        }
    }
}

The root class would look something like this:

public class Root {
    ...
    public OptionsBean getOptions() { ... }
    public void setOptions(OptionsBean value} { ... }
    ...
}

And I'd like my YAML to look like this:

name: Colored Box
options: COLOR
height: 100
width: 100

I know I can use tags to get something like what I want, but I'd rather not have to use an explicit tag.

1

There are 1 answers

0
tecywiz121 On

I seemed to have solved my own problem, although I don't know how "correct" it is:

private static class MyConstructor extends Constructor {

    public MyConstructor(Class<? extends Object> theRoot) {
        super(theRoot);

        this.yamlClassConstructors.put(NodeId.scalar, new ConstructCustom());
    }

    private class ConstructCustom extends ConstructScalar {

        @Override
        public Object construct(Node node) {
            if (node.getType().equals(OptionsBean.getClass())) {
                return OptionsBean.valueOf(node.getValue());
            } else {
                return super.construct(node);
            }
        }
    }
}