mercredi 26 juin 2019

Java Reflection - Copy nested objects values

I have an object, that might have other objects or list of objects. Is there a way to iterate through these objects to copy their values into a new object? What I want to do is merge 2 objects to update a document in my DB, so I don't want the null values.

So far I've reached the way to do a shallow copy with no nulls value for any object with this:

public Object merge(Object target) {
    try {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field f: fields) {
            if (f.get(this) != null) {
                f.set(target, f.get(this));
                System.out.println(f.get(this));
            }
        }
    } catch (IllegalAccessException e) {
        return target;
    }
    return target;
}

Problem Statement: But now, how can I handle nested objects? Like a List of Car objects for example?





Aucun commentaire:

Enregistrer un commentaire