序言java
近期在工做中管理代碼時發現,在項目中從Dao層到Service層數據傳遞中經過大量的get(),set()方法去一個一個的去拿值去賦值,致使代碼篇幅過長,對此甚是討厭,而且嚴重消耗開發時間。起初找過些關於這塊的資料,如今大部分都是Entity類和Dto類的屬性名相同的前提下,利用反射實現,太侷限了,若是要改爲同名,按目前項目的程度去整改工做量太大,不現實。後面看了Spring註解的實現,而後結合找到反射實現資料,突想奇發嘗試着用自定義註解+反射方式的去實現,事實證實這方法是可行的。故分享至此,但願能幫到你們。面試
總體實現三步驟:1.自定義註解 2.工具類方法實現反射 3.使用(測試)sql
1.自定義註解apache
1 import java.lang.annotation.*; 2 3 @Target({ElementType.FIELD,ElementType.TYPE}) //Target 註解的使用域,FIELD表示使用在屬性上面,TYPE表示使用在類上面 4 @Retention(RetentionPolicy.RUNTIME) //Retention 設置註解的生命週期 ,這裏定義爲RetentionPolicy.RUNTIME 很是關鍵 5 @Documented 6 public @interface RelMapper { 7 //自定義屬性 8 String value() default ""; 9 String type() default ""; // value : status(標記屬性值爲Y/N的屬性) / date(標記屬性類型爲時間) 10 }
自定義屬性,你們能夠根據本身項目中的需求增長不一樣的屬性。安全
2.工具類方法實現架構
1 import java.lang.reflect.Field; 2 import java.lang.reflect.Method; 3 import java.sql.Timestamp; 4 import java.util.Date; 5 import org.apache.commons.lang.StringUtils; 6 import com.ctccbs.common.annotation.RelMapper; 7 8 public class RelationMapperUtils { 9 /** 10 * Entity and Dto Mapper 11 * @param entry 12 * @param dto 13 * @param enToDto 14 * ture : Entity To Dto (defult) 15 * false : Dto To Entry 16 * Rule: 17 * 實現相互轉換前提: Dto field name(dto和entry的field name相同而且 類上有@RelMapper) 或 field的@RelMapper(value="Entity field name") 知足其一便可轉換 18 * @return 19 * @throws Exception 20 */ 21 public static Object entryAndDtoMapper(Object entity, Object dto) throws Exception{ 22 return EnAndDtoMapper(entity, dto,true); 23 } 24 25 public static Object entryAndDtoMapper(Object entity, Object dto,boolean enToDto) throws Exception{ 26 return EnAndDtoMapper(entity, dto,false); 27 } 28 //last version 29 public static Object EnAndDtoMapper(Object entry, Object dto,boolean enToDto) throws Exception{ 30 if(enToDto == true ? entry == null : dto == null){ return null;} 31 Class<? extends Object> entryclazz = entry.getClass(); //獲取entity類 32 Class<? extends Object> dtoclazz = dto.getClass(); //獲取dto類 33 boolean dtoExistAnno = dtoclazz.isAnnotationPresent(RelMapper.class); //判斷類上面是否有自定義註解 34 Field [] dtofds = dtoclazz.getDeclaredFields(); //dto fields 35 Field [] entryfds = entryclazz.getDeclaredFields(); //entity fields 36 Method entrys[] = entryclazz.getDeclaredMethods(); //entity methods 37 Method dtos[] = dtoclazz.getDeclaredMethods(); //dto methods 38 String mName,fieldName,dtoFieldType=null,entFieldType=null,dtoMapName = null,dtoFieldName =null;Object value = null; 39 for(Method m : (enToDto ? dtos : entrys)) { //當 enToDto=true 此時是Entity轉爲Dto,遍歷dto的屬性 40 if((mName=m.getName()).startsWith("set")) { //只進set方法 41 fieldName = mName.toLowerCase().charAt(3) + mName.substring(4,mName.length()); //經過set方法得到dto的屬性名 42 tohere: 43 for(Field fd: dtofds) { 44 fd.setAccessible(true); //setAccessible是啓用和禁用訪問安全檢查的開關 45 if(fd.isAnnotationPresent(RelMapper.class)||dtoExistAnno){ //判斷field上註解或類上面註解是否存在 46 //獲取與Entity屬性相匹配的映射值(兩種狀況:1.該field上註解的value值(Entity的field name 和Dto 的field name 不一樣) 2.該field自己(自己則是Entity的field name 和Dto 的field name 相同)) 47 dtoMapName = fd.isAnnotationPresent(RelMapper.class) ? (fd.getAnnotation(RelMapper.class).value().toString().equals("")?fd.getName().toString():fd.getAnnotation(RelMapper.class).value().toString()):fd.getName().toString(); 48 if(((enToDto ? fd.getName() : dtoMapName)).toString().equals(fieldName)) { 49 dtoFieldType = fd.getGenericType().toString().substring(fd.getGenericType().toString().lastIndexOf(".") + 1); // 獲取dto屬性的類型(如 private String field 結果 = String) 50 for(Field fe : entryfds) { 51 fe.setAccessible(true); 52 if(fe.getName().toString().equals(enToDto ? dtoMapName : fieldName) ) {//遍歷Entity類的屬性與dto屬性註解中的value值匹配 53 entFieldType = fe.getGenericType().toString().substring(fe.getGenericType().toString().lastIndexOf(".") + 1); //獲取Entity類屬性類型 54 dtoFieldName = enToDto ? dtoMapName : fd.getName().toString(); 55 break tohere; 56 } 57 } 58 } 59 } 60 } 61 if(dtoFieldName!= null && !dtoFieldName.equals("null")) { 62 for(Method md : (enToDto ? entrys : dtos)) { 63 if(md.getName().toUpperCase().equals("GET"+dtoFieldName.toUpperCase())){ 64 dtoFieldName = null; 65 if(md.invoke(enToDto ? entry : dto) == null) { break;} //去空操做 66 //Entity類field 與Dto類field類型不一致經過TypeProcessor處理轉換 67 value = (entFieldType.equals(dtoFieldType))? md.invoke(enToDto ? entry : dto) :TypeProcessor(entFieldType, dtoFieldType,md.invoke(enToDto ? entry : dto),enToDto ? true : false); 68 m.invoke(enToDto ? dto : entry, value); //獲得field的值 經過invoke()賦值給要轉換類的對應屬性 69 value = null; 70 break; 71 } 72 } 73 } 74 } 75 } 76 return enToDto ? dto : entry; 77 } 78 79 //類型轉換處理 80 public static Object TypeProcessor(String entFieldType,String dtoFieldType, Object obj,boolean enToDto) { 81 if(entFieldType.equals(dtoFieldType)) return obj; 82 83 if(!entFieldType.equals(dtoFieldType)) { 84 switch(entFieldType) { 85 case "Date": 86 return (enToDto)?TypeConverter.dateToString((Date) obj):TypeConverter.stringToDate(obj.toString()); 87 case "Timestamp": 88 return TypeConverter.timestampToTimestampString((Timestamp)obj); 89 case "Integer": 90 return (enToDto) ? obj.toString() : Integer.parseInt((String)obj) ; 91 } 92 } 93 return obj; 94 }
上面EnAndDtoMapper()方法的實現是Entity和Dto之間互相轉換結合在一塊兒,enToDto = true 表示的是Entity轉Dto實現,false則相反。app
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的代碼,省事!!!
你們若是還有其餘的需求均可以往方法中添加,來達到適合項目的需求,總體下來擴展性算還不錯。
但願對你們有所幫助,有不解或不足的代碼歡迎點出。你們一塊兒進步
歡迎工做一到五年的Java工程師朋友們加入Java架構開發:855801563
本羣提供免費的學習指導 架構資料 以及免費的解答
不懂得問題均可以在本羣提出來 以後還會有職業生涯規劃以及面試指導
同時你們能夠多多關注一下小編 純乾貨 你們一塊兒學習進步