我有一个场景,我必须使用 MapStruct 将 Resource
对象(来自网络请求)转换为 RealmObject
对象(数据层)处理对象映射。我正在尝试创建一个通用的 Mapper
接口(interface),以防止必须为每个资源定义自定义映射器,如下所示:
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import io.realm.RealmObject;
import moe.banana.jsonapi2.Resource;
@Mapper
public interface ResourceMapper <T extends Resource, I extends RealmObject> {
ResourceMapper INSTANCE = Mappers.getMapper(ResourceMapper.class);
I resourceToRealm(T resource);
}
但这会导致构建错误(但是编译成功):
Error:(13, 4) error: Can't generate mapping method for a generic type variable source.
这不可能吗?如果没有,我将不得不为每个 Resource
创建一个自定义映射器,并使用 switch
告诉反序列化器根据类类型等使用哪个映射器......它可能会变得丑陋并且不会导致非常干燥的代码。他们的documentation对此不是很清楚。
最佳答案
编辑 1:
来自文档,
The generated implementation uses plain Java method invocations for mapping between source and target objects, i.e. there is no reflection involved. By default, properties are mapped if they have the same name in source and target, but this and many other aspects can be controlled using @Mapping and a handful of other annotations.
我怀疑这样的映射器契约(Contract)是否可行。 我们无法判断哪种类型将作为这种自动生成的结果被实例化。
有两个预期结果
- 生成类型为 I 的类(我假设这是您所期望的) - Currently not possible
- 生成一个类型为 RealmObject 的类,并且只映射基本方法属性和方法
如果您想要第二个结果,请按照 this 进行操作
关于java - 在 Android 中使用 MapStruct 来映射泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45248330/