java: 如何复制不同参数类型的值

java: how to duplicate value with different parameter type

我的 spring 代码有问题,我正在努力寻找解决方案。

我想使用不同的参数类型将我的值从 dto 解析到模型,反之亦然。

这是SC: 用户模型:

public Class UserModel {
private int userId;
private Date dob;
//setter getter
}

UserDto:

public Class UserDto {
private String userId;
private String dob;
//setter getter
}

我试了很多方法,比如用ObjectMapper和PropertyUtilsBean,一直报错

你们谁有最好的解决方案?请帮忙

这个解决方案适合我:

import org.apache.commons.beanutils.*;
import org.apache.commons.beanutils.converters.DateConverter;

import java.util.Date;

public class Main {

    public static void main(String[] args) throws Exception {
        DateConverter converter = new DateConverter();
        converter.setPattern("yyyy-MM-dd");

        ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
        convertUtilsBean.register(converter, Date.class);

        BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());

        UserDto dto = new UserDto("42", "2018-11-14");
        System.out.println("dto.getUserId() = " + dto.getUserId());
        System.out.println("dto.getDob() = " + dto.getDob());

        UserModel model = new UserModel();
        beanUtilsBean.copyProperties(model, dto);

        System.out.println("model.getUserId() = " + model.getUserId());
        System.out.println("model.getDob() = " + model.getDob());
    }

}

您可以找到完整的示例源代码 here