How to merge two complex objects in java

前端 未结 5 1347
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 23:23

I have two java objects and I want to merge them into single object. Problem is the two objects does not contain plain primitive type properties(fields) they contain complex

5条回答
  •  孤街浪徒
    2021-01-01 23:57

    import java.util.Objects;
    import java.util.function.Consumer;
    import java.util.function.Supplier;
    
    public final class PropertyMerger {
    
        public static  void mergeProperty(
                Supplier sourceGetter,
                Supplier targetGetter,
                Consumer targetSetter
        ) {
            var source = sourceGetter.get();
            var target = targetGetter.get();
    
            if (!Objects.equals(source, target)) {
                targetSetter.accept(source);
            }
        }
    
    }
    

    Somwhere in your code:

    PropertyMerger.mergeProperty(facebookOAuth2User::getId, existingFacebookOAuth2UserDB::getFacebookId, existingFacebookOAuth2UserDB::setFacebookId);
    PropertyMerger.mergeProperty(facebookOAuth2User::getName, existingFacebookOAuth2UserDB::getName, existingFacebookOAuth2UserDB::setName);
    

提交回复
热议问题