java-转换类

gywdnpxw  于 2021-07-14  发布在  Java
关注(0)|答案(3)|浏览(316)

我有两门课:

public class Customer {
    private String firstname;
    private String lastname;
}

public class Buyer {
    private String firstname;
    private String lastname;
}

我希望这两个类都转换为以下类的:

public class CustomerDTO {
   private String firstname;
   private String lastname;
}

我不能为类或其他东西使用公共接口。有没有一种方法可以用一个转换器类将customer和buyer都转换为customer dto类?

bt1cpqcv

bt1cpqcv1#

不能转换(Map)两个类( Customer , Buyer )到第三个( CustomerDTO )因为没有两个类共享的公共类型(即接口)。java不使用duck类型,因此不能依赖于类看起来相似的事实。编译器没有看到。
话虽如此,您至少可以自动生成所需的Map器。一个选项是mapstruct。在您的情况下,Map将非常简单(基于文档):

@Mapper
public interface CustomerMapper {

    CustomerDto toCustomerDto(Customer customer);

    CustomerDto toCustomerDto(Buyer buyer);
}

mapstruct是一个编译时依赖项:它将在编译时为您生成Map程序,以便您可以查看它们。
感谢royal bg建议使用方法重载( toCustomerDto )一个更干净的解决方案。

sqougxex

sqougxex2#

例如,可以使用模型Map器http://modelmapper.org/getting-started/

ryoqjall

ryoqjall3#

这是一个示例代码,您可以将其添加到客户和买家的dto代码中

public UserDTO(Cutomer user) {
        this.id = user.getId();
        this.login = user.getLogin();
        this.firstName = user.getFirstName();
        this.lastName = user.getLastName();
        this.email = user.getEmail();
        this.authorities = user.getAuthorities().stream()
            .map(Authority::getName)
            .collect(Collectors.toSet());
    }

相关问题