作者:Mr_Precious
链接:
https://www.cnblogs.com/scale-lai/p/10164634.html
序言
近期在工作中管理代码时发现,在项目中从Dao层到Service层数据传递中通过大量的get(),set()方法去一个一个的去拿值去赋值,导致代码篇幅过长,对此甚是讨厌,并且严重消耗开发时间。
起初找过些关于这块的资料,现在大部分都是Entity类和Dto类的属性名相同的前提下,利用反射实现,太局限了,如果要改成同名,按目前项目的程度去整改工作量太大,不现实。
后面看了Spring注解的实现,然后结合找到反射实现资料,突想奇发尝试着用自定义注解+反射方式的去实现,事实证明这方法是可行的。故分享至此,希望能帮到大家。
整体实现三步骤:
- 自定义注解
- 工具类方法实现反射
- 使用(测试)
1、自定义注解
import java.lang.annotation.*;
@Target({ElementType.FIELD,ElementType.TYPE}) //Target 注解的使用域,FIELD表示使用在属性上面,TYPE表示使用在类上面
@Retention(RetentionPolicy.RUNTIME) //Retention 设置注解的生命周期 ,这里定义为RetentionPolicy.RUNTIME 非常关键
@Documented
public @interface RelMapper {
//自定义属性
String value() default "";
String type() default ""; // value : status(标记属性值为Y/N的属性) / date(标记属性类型为时间)
}
自定义属性,大家可以根据自己项目中的需求增加不同的属性。
2、工具类方法实现
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import com.ctccbs.common.annotation.RelMapper;
public class RelationMapperUtils {
/**
* Entity and Dto Mapper
* @param entry
* @param dto
* @param enToDto
* ture : Entity To Dto (defult)
* false : Dto To Entry
* Rule:
* 实现相互转换前提: Dto field name(dto和entry的field name相同并且 类上有@RelMapper) 或 field的@RelMapper(value="Entity field name") 满足其一即可转换
* @return
* @throws Exception
*/
public static Object entryAndDtoMapper(Object entity, Object dto) throws Exception{
return EnAndDtoMapper(entity, dto,true);
}
public static Object entryAndDtoMapper(Object entity, Object dto,boolean enToDto) throws Exception{
return EnAndDtoMapper(entity, dto,false);
}
//last version
public static Object EnAndDtoMapper(Object entry, Object dto,boolean enToDto) throws Exception{
if(enToDto == true ? entry == null : dto == null){ return null;}
Class extends Object> entryclazz = entry.getClass(); //获取entity类
Class extends Object> dtoclazz = dto.getClass(); //获取dto类
boolean dtoExistAnno = dtoclazz.isAnnotationPresent(RelMapper.class); //判断类上面是否有自定义注解
Field [] dtofds = dtoclazz.getDeclaredFields(); //dto fields
Field [] entryfds = entryclazz.getDeclaredFields(); //entity fields
Method entrys[] = entryclazz.getDeclaredMethods(); //entity methods
Method dtos[] = dtoclazz.getDeclaredMethods(); //dto methods
String mName,fieldName,dtoFieldType=null,entFieldType=null,dtoMapName = null,dtoFieldName =null;Object value = null;
for(Method m : (enToDto ? dtos : entrys)) { //当 enToDto=true 此时是Entity转为Dto,遍历dto的属性
if((mName=m.getName()).startsWith("set")) { //只进set方法
fieldName = mName.toLowerCase().charAt(3) + mName.substring(4,mName.length()); //通过set方法获得dto的属性名
tohere:
for(Field fd: dtofds) {
fd.setAccessible(true); //setAccessible是启用和禁用访问安全检查的开关
if(fd.isAnnotationPresent(RelMapper.class)||dtoExistAnno){ //判断field上注解或类上面注解是否存在
//获取与Entity属性相匹配的映射值(两种情况:1.该field上注解的value值(Entity的field name 和Dto 的field name 不同) 2.该field本身(本身则是Entity的field name 和Dto 的field name 相同))
dtoMapName = fd.isAnnotationPresent(RelMapper.class) ? (fd.getAnnotation(RelMapper.class).value().toString().equals("")?fd.getName().toString():fd.getAnnotation(RelMapper.class).value().toString()):fd.getName().toString();
if(((enToDto ? fd.getName() : dtoMapName)).toString().equals(fieldName)) {
dtoFieldType = fd.getGenericType().toString().substring(fd.getGenericType().toString().lastIndexOf(".") + 1); // 获取dto属性的类型(如 private String field 结果 = String)
for(Field fe : entryfds) {
fe.setAccessible(true);
if(fe.getName().toString().equals(enToDto ? dtoMapName : fieldName) ) {//遍历Entity类的属性与dto属性注解中的value值匹配
entFieldType = fe.getGenericType().toString().substring(fe.getGenericType().toString().lastIndexOf(".") + 1); //获取Entity类属性类型
dtoFieldName = enToDto ? dtoMapName : fd.getName().toString();
break tohere;
}
}
}
}
}
if(dtoFieldName!= null && !dtoFieldName.equals("null")) {
for(Method md : (enToDto ? entrys : dtos)) {
if(md.getName().toUpperCase().equals("GET"+dtoFieldName.toUpperCase())){
dtoFieldName = null;
if(md.invoke(enToDto ? entry : dto) == null) { break;} //去空操作
//Entity类field 与Dto类field类型不一致通过TypeProcessor处理转换
value = (entFieldType.equals(dtoFieldType))? md.invoke(enToDto ? entry : dto) :TypeProcessor(entFieldType, dtoFieldType,md.invoke(enToDto ? entry : dto),enToDto ? true : false);
m.invoke(enToDto ? dto : entry, value); //得到field的值 通过invoke()赋值给要转换类的对应属性
value = null;
break;
}
}
}
}
}
return enToDto ? dto : entry;
}
//类型转换处理
public static Object TypeProcessor(String entFieldType,String dtoFieldType, Object obj,boolean enToDto) {
if(entFieldType.equals(dtoFieldType)) return obj;
if(!entFieldType.equals(dtoFieldType)) {
switch(entFieldType) {
case "Date":
return (enToDto)?TypeConverter.dateToString((Date) obj):TypeConverter.stringToDate(obj.toString());
case "Timestamp":
return TypeConverter.timestampToTimestampString((Timestamp)obj);
case "Integer":
return (enToDto) ? obj.toString() : Integer.parseInt((String)obj) ;
}
}
return obj;
}
上面EnAndDtoMapper()方法的实现是Entity和Dto之间互相转换结合在一起,enToDto = true 表示的是Entity转Dto实现,false则相反。
3、如何使用?
1)Entity类 与 Dto类对应
2)调用
public static void main(String[] args) {
//Entity数据转成Dto数据集
Person person = dao.getPersonRecord();
RelationMapperUtils.entryAndDtoMapper(person,new PersonDto());
//Dto数据转成Entity数据
RelationMapperUtils.entryAndDtoMapper(new Person(),personDto,false);
}
以上便能自动实现数据的转换,大量减少get,set的代码,省事!!!
大家如果还有其他的需求都可以往方法中添加,来达到适合项目的需求,整体下来扩展性算还不错。
本文暂时没有评论,来添加一个吧(●'◡'●)