2

In my project I have the following model:

public class Object1 extends ObjectBase {
    private Value1 specific1;
}

public class Object2 extends ObjectBase {
    private Value2 specific2;
}

public abstract class ObjectBase {
    private String value1;
    private String value2;
    private String value3;
}

public class Source {
    private String value1;
    private String value2;
    private String value3;
}

I need to make a way of mapping a Source object into either of Object1 or Object2. Is it possible to have a common function for setting the ObjectBase values? Previously, this was done by creating a new instance of either, and then send it to something like the following:

public static void convertToObjectBase(Source source, ObjectBase objectBase) {
    objectBase.setValue1(source.getValue1);
    objectBase.setValue2(source.getValue2);
    objectBase.setValue3(source.getValue3);
}

This latter way, editing in place, seems wrong to me. Do you know a better way of doing this, without having to replicate all the setters for ObjectBase for each case? There's something like 40 values that have to be mapped in each case, requiring some internal logic, but this would be the same for both Object1 and Object2.

I'm thinking that generics could be the way to go here, but I'm not completely sure.

Edit: I had some misleading value names, updated these.

1 Answers1

-1

You can try using instanceof operator in your mapper. Something like

if (objectBase instanceof Object1) {
        //do something 
}
else if (objectBase instanceof Object2) {
        //do something else
}

. . .

This way you can map whatever properties you want to map for child class using same mapper.

user3731930
  • 137
  • 1
  • 1
  • 8