0

I have two instances of the same class: one has values in all its fields and the other just some fields (the other fields are null). I want to update the values of the first object using the second's values, only if it isn't null. Something like this:

class MyObject {
    private void setObject(MyObject other) {
        if (other.getField1() != null) this.field1 = other.getField1();
        .....                
    }
}

The setObject method's code is really long when I have a lot of fields, and I need to implement that method in all my objects. I was wondering if it can be done on a more generic way: get object as argument -> iterate over its fields -> populate if isn't null.

I tried usage of some reflection to do this, unsuccessfully for now.

Sabrina
  • 1,621
  • 2
  • 11
  • 16
  • It can be done with reflection. Include the code you tried in the question. – cpp beginner Oct 27 '17 at 19:44
  • Your question is basically a special case of https://stackoverflow.com/questions/1667854/copy-all-values-from-fields-in-one-class-to-another-through-reflection, except that the source and destination class is the same. – azurefrog Oct 27 '17 at 19:46
  • @azurefrog well, not exactly, since I do need to perform some logic before coping the values (null check) – Sabrina Oct 28 '17 at 04:31

1 Answers1

2

I think you need something like this

class MyObject{

public Integer a;
public Integer b;
public Integer c;
}

public class Reflect {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub
        MyObject a = new MyObject();
        a.a=4;
        MyObject b = new MyObject();
        b.a=2;
        b.b=3;
        b.c=5;
        GenericInstancePopulateMethod(MyObject.class, a, b);

        System.out.println(a.b);//this prints 3 as expected
        System.out.println(a.a);//this prints 4 as expected
    }
    static void GenericInstancePopulateMethod(Class<MyObject> clz, MyObject a, MyObject b) throws IllegalArgumentException, IllegalAccessException{

        Field[] fields = clz.getFields();

        for(Field f : fields){
        if(f.get(a) == null)
            f.set(a,  f.get(b)) ;//a fields  are assigned b fields' values
        }
    }
}

I used Field[]but you can use Method[]instead if you have getter and setter methods.

dsp_user
  • 2,061
  • 2
  • 16
  • 23