通用DTO泛型接口
public interface DTOConvert<S,T>{
public T convert(S s);
}
public class UserDTOConvert implements DTOConvert {
@Override
public User convert(UserDTO userDTO) {
BeanUtils.copyProperties(source,target);
return target;
}
}
二级封装
public class UserInputDTO {
private String username;
private int age;
//get and set
public User convertToUser(){
UserInputDTOConvert userInputDTOConvert = new UserInputDTOConvert();
User convert = userInputDTOConvert.convert(this);
return convert;
}
private static class UserInputDTOConvert implements DTOConvert<UserInputDTO,User> {
@Override
public User convert(UserInputDTO userInputDTO) {
User user = new User();
BeanUtils.copyProperties(userInputDTO,user);
return user;
}
}
}
继承guava的抽象类Covert<A,B> ,完成正向转换和逆向转换
public class UserDTO {
private String username;
private int age;
//getter and setter
public User convertToUser(){
UserDTOConvert userDTOConvert = new UserDTOConvert();
User convert = userDTOConvert.convert(this);
return convert;
}
public UserDTO convertFor(User user){
UserDTOConvert userDTOConvert = new UserDTOConvert();
UserDTO convert = userDTOConvert.reverse().convert(user);
return convert;
}
private static class UserDTOConvert extends Converter<UserDTO, User> {
@Override
protected User doForward(UserDTO userDTO) {
User user = new User();
BeanUtils.copyProperties(userDTO,user);
return user;
}
@Override
protected UserDTO doBackward(User user) {
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(user,userDTO);
return userDTO;
}
}
}
转换Util可以参考网络上的性能测试与实际结合选择:
文章:https://www.javazhiyin.com/81344.html
后起之秀还有MapStruct,可以了解下。