泛型父类中获取子类的泛型,延伸工具类

小灰灰 2022-09-01 08:30 289阅读 0赞

接口:

  1. public interface Convertable<T,R> extends Serializable {
  2. /**
  3. * 转换为R对象
  4. */
  5. R convertTo() throws Exception;
  6. /**
  7. * T对象赋值
  8. */
  9. void convertFor(R r) throws Exception;
  10. }

接口实现:

  1. public abstract class ConvertableImpl<T, R> implements Convertable<T, R> {
  2. /**
  3. * 将R转换为T类型
  4. */
  5. @Override
  6. public R convertTo() throws Exception {
  7. Class<R> classR = null;
  8. Type genericSuperclass = this.getClass().getGenericSuperclass();
  9. if (genericSuperclass instanceof ParameterizedType) {
  10. ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
  11. // size=2,第一个是T,第二个是R
  12. Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  13. classR = (Class<R>) actualTypeArguments[1];
  14. }
  15. R r = classR.newInstance();
  16. BeanUtils.copyProperties(this, r);
  17. return r;
  18. }
  19. /**
  20. * T对象赋值
  21. */
  22. @Override
  23. public void convertFor(R r) throws Exception {
  24. BeanUtils.copyProperties(r, this);
  25. }
  26. }

DTO:

  1. @Data
  2. public class UserDto extends ConvertableImpl<UserDto, UserPo> {
  3. private String id;
  4. private String username;
  5. private String password;
  6. private String name;
  7. private String phone;
  8. }

DO:

  1. @Data
  2. public class UserPo extends ConvertableImpl<UserPo, UserVo> {
  3. private String id;
  4. private String username;
  5. private String password;
  6. private String name;
  7. private String phone;
  8. private Date createTime;
  9. private Date updateTime;
  10. private boolean enable;
  11. }

VO:

  1. @Data
  2. public class UserVo {
  3. private String id;
  4. private String username;
  5. private String name;
  6. private String phone;
  7. }

测试代码:

  1. /**
  2. * 假设一个正常接口保存流程
  3. * @param args
  4. */
  5. public static void main(String[] args) throws Exception {
  6. // 1、接口进来的入参
  7. UserDto dto = new UserDto();
  8. dto.setName("小明");
  9. dto.setPhone("12312312313");
  10. dto.setUsername("xiaoming");
  11. dto.setPassword("123456");
  12. // 2、DTO ==》DO
  13. UserPo po = dto.convertTo();
  14. po.setCreateTime(new Date());
  15. po.setUpdateTime(new Date());
  16. // 3、save po保存成功,回写ID""
  17. po.setId("1");
  18. // 4、PO ==》VO
  19. UserVo vo = po.convertTo();
  20. System.out.println(vo.getId());
  21. }

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读

    相关 -、接口、方法

    为什么要使用泛型?优点在哪里? 使用java泛型的动机在编译时检测出错误。 一、泛型方法 可以为静态方法定义为泛型类型! 1、非受限泛型:<T> 等价于受限泛型<T e