泛型父类中获取子类的泛型,延伸工具类
接口:
public interface Convertable<T,R> extends Serializable {
/**
* 转换为R对象
*/
R convertTo() throws Exception;
/**
* T对象赋值
*/
void convertFor(R r) throws Exception;
}
接口实现:
public abstract class ConvertableImpl<T, R> implements Convertable<T, R> {
/**
* 将R转换为T类型
*/
@Override
public R convertTo() throws Exception {
Class<R> classR = null;
Type genericSuperclass = this.getClass().getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
// size=2,第一个是T,第二个是R
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
classR = (Class<R>) actualTypeArguments[1];
}
R r = classR.newInstance();
BeanUtils.copyProperties(this, r);
return r;
}
/**
* T对象赋值
*/
@Override
public void convertFor(R r) throws Exception {
BeanUtils.copyProperties(r, this);
}
}
DTO:
@Data
public class UserDto extends ConvertableImpl<UserDto, UserPo> {
private String id;
private String username;
private String password;
private String name;
private String phone;
}
DO:
@Data
public class UserPo extends ConvertableImpl<UserPo, UserVo> {
private String id;
private String username;
private String password;
private String name;
private String phone;
private Date createTime;
private Date updateTime;
private boolean enable;
}
VO:
@Data
public class UserVo {
private String id;
private String username;
private String name;
private String phone;
}
测试代码:
/**
* 假设一个正常接口保存流程
* @param args
*/
public static void main(String[] args) throws Exception {
// 1、接口进来的入参
UserDto dto = new UserDto();
dto.setName("小明");
dto.setPhone("12312312313");
dto.setUsername("xiaoming");
dto.setPassword("123456");
// 2、DTO ==》DO
UserPo po = dto.convertTo();
po.setCreateTime(new Date());
po.setUpdateTime(new Date());
// 3、save po保存成功,回写ID""
po.setId("1");
// 4、PO ==》VO
UserVo vo = po.convertTo();
System.out.println(vo.getId());
}
还没有评论,来说两句吧...