osglworks / java-tool

Some simple common Java utilities
Apache License 2.0
52 stars 18 forks source link

Bean copy utility shall not create new target component instance if it exists #105

Closed greenlaw110 closed 6 years ago

greenlaw110 commented 6 years ago

Found on osgl-tool-1.14.0

Test code:

    public static class Foo {
        Map<String, String> map = new HashMap<>();
    }

    public static class Bar {
        Map<String, String> map = new LinkedHashMap<>();
    }

    @Test
    public void test1() {
        Foo foo = new Foo();
        foo.map.put("X", "10");
        Bar bar = $.deepCopy(foo).to(Bar.class);
        eq("10", bar.map.get("X"));
        yes(bar.map instanceof LinkedHashMap, "It shall not change bar.map instance");
    }

Running test1 will show error java.lang.AssertionError: It shall not change bar.map instance

greenlaw110 commented 6 years ago

Okay, so this design is made in purpose actually. Think about if a target Map is an immutable map, then we can't put anything inside it. As the type is declared as Map, we assume it is safe to replace the implementation type to HashMap. However this make it a bit loose when target type is things like LinkedHashMap, the replacement actually changes the behavior to some extend.

The fix will take care of the LinkedHashMap, LinkedHashSet case now.