TheElectronWill / night-config

Powerful java configuration library for toml, yaml, hocon, json and in-memory configurations. Serialization/deserialization framework.
GNU Lesser General Public License v3.0
242 stars 28 forks source link

@PreserveNotNull doesn't work for custom Classes #131

Closed brainbytes42 closed 8 months ago

brainbytes42 commented 1 year ago

I'm modeling a nested configuration structure, which will contain defaults for some values. In the example below, I have a simple string foo, for which this works perfectly, if I disable the setting in config. But for bar, the default Object is always created and preserved, so even when bar.barValue is set, it won't be set to the Bar-Object. If I disable Foo's @PreserveNotNull, the BarValue is correctly set. I would expect bar to be preserved only, if there is nothing set in the config, or even better recursively applied so that single missing values may have their default preserved, but anything set to the config file will be present in the object.

    public static void main(String[] args) {
        Config config = Config.inMemory();
        config.set("fooValue", "FooValue");   // try disable this line
        config.set("bar.barValue", "BarValue");   // try disable this line

        Foo object = new ObjectConverter().toObject(config, Foo::new);
        System.out.println("Object: " + object);
    }

    @PreserveNotNull   // try disable this line
    static class Foo {

        String fooValue = "FooDefault";

        Bar bar = new Bar();

        @Override
        public String toString() {
            return "Foo{" + "fooValue='" + fooValue + '\'' + ", bar=" + bar + '}';
        }

        @PreserveNotNull
        static class Bar {

            String barValue = "BarDefault";

            @Override
            public String toString() {
                return "Bar{" + "barValue='" + barValue + '\'' + '}';
            }

        }

    }

    // OUTPUT > Object: Foo{fooValue='FooValue', bar=Bar{barValue='BarDefault'}}
TheElectronWill commented 1 year ago

Thanks for reporting! I'll do some testing and report back here :)