Merging two objects in Java

前端 未结 8 791
离开以前
离开以前 2020-12-15 23:25

I have two objects of same type.

Class A {
  String a;
  List b;
  int c;
}

A obj1 = new A();
A obj2 = new A();

obj1 => {a = \"hello\"; b = null; c = 10         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-16 00:18

    Just accommodating boolean sync. and case sensitive(camel notation)

    public boolean merge(Object obj){
    
        if(this.equals(obj)){
            return false;
        }
    
        if(!obj.getClass().isAssignableFrom(this.getClass())){
            return false;
        }
    
        Method[] methods = obj.getClass().getMethods();
    
        for(Method fromMethod: methods){
            if(fromMethod.getDeclaringClass().equals(obj.getClass())
                    && (fromMethod.getName().matches("^get[A-Z].*$")||fromMethod.getName().matches("^is[A-Z].*$"))){
    
                String fromName = fromMethod.getName();
                String toName ;
                if(fromName.matches("^get[A-Z].*")){
                    toName = fromName.replace("get", "set");
                }else{
                    toName = fromName.replace("is", "set");
                }
    
                try {
                    Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType());
                    Object value = fromMethod.invoke(this, (Object[])null);
                    if(value != null){
                        toMetod.invoke(obj, value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }
    
        return true;
    }
    

提交回复
热议问题