[英]I have an abstract class and two extensions, can I have a common mapper?
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
. 我需要一种将Source
对象映射到Object1
或Object2
。 Is it possible to have a common function for setting the ObjectBase
values? 是否可以具有用于设置ObjectBase
值的通用功能? 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? 您是否知道一种更好的方法,而不必为每种情况复制ObjectBase
所有设置方法? 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
. 每种情况下都需要映射约40个值,这需要一些内部逻辑,但是Object1
和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. 编辑:我有一些误导的值名称,更新了这些。
You can try using instanceof operator in your mapper. 您可以尝试在映射器中使用instanceof运算符。 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. 这样,您可以使用相同的映射器映射要为子类映射的任何属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.