java - 在 Android 中使用 MapStruct 来映射泛型类型?

标签 java android generics mapping mapstruct

我有一个场景,我必须使用 MapStructResource 对象(来自网络请求)转换为 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)是否可行。 我们无法判断哪种类型将作为这种自动生成的结果被实例化。

有两个预期结果

  1. 生成类型为 I 的类(我假设这是您所期望的) - Currently not possible
  2. 生成一个类型为 RealmObject 的类,并且只映射基本方法属性和方法

如果您想要第二个结果,请按照 this 进行操作

关于java - 在 Android 中使用 MapStruct 来映射泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45248330/

相关文章:

java - 如何使用java中的反射查找类中使用其他接口(interface)扩展其他类的所有接口(interface)

java - 兰特流的高性能缓冲

java - 链接多个 CompletableFuture 时加括号的正确方法是什么?

java - javadoc到底是什么?

android - 我可以从我的应用程序访问 Android 中的受信任证书条目吗

快速通用字典功能

java - 连接并返回 Observable

android - 如何在android中将彩色图像位图转换为黑白图像位图?

Java泛型不完全理解

java - 泛型中的类型安全