1、思考
- 無論是ssm框架,還是springboot,只要使用mybatis都會使用到對象關係映射;
- 實際項目中,往往除了表對象的基礎屬性,還需要加很多其他的屬性;除了表的基礎屬性,不同的接口,添加屬性又不同,造成類無用的屬性太多,影響美觀;
- 這時候想到了繼承,表對象做爲父類,其他具體的業務類繼承表對象,邏輯清晰,代碼明瞭,複用性增加;
- 但是問題又來了,在java中父類不能強轉成子類,表對象有時候10+的屬性,或者更多,這時候無論是構造方法,還是set,寫着都好累,而且很醜。
- 最開始查了很多網上的資料,父類是可以轉子類,但是都不是太適合,我想的是更加通用,簡單;
- 最後想到兩種辦法,一種是反射,一種是json。
- 反射原理比較簡單,循環賦值。反射不止適用於父類轉子類,只要具有相同屬性的都可以轉,都可以賦值。
2、工具類
先上代碼,可直接食用
package com.utils.v2;
import com.alibaba.fastjson.JSONObject;
import java.lang.reflect.Field;
/**
* @Description: 父類強轉子類
* @Author: zx
* @Time: 2019-12-18 17:03
**/
public class StrongParentSubclass {
/**
* @Author zx
* @Description 反射循環賦值
* @Date 2019/12/18 18:32
* @Param [parent, subclass]
**/
public static Object parentSubclass(Object parent,Object subclass){
Field[] parents = parent.getClass().getDeclaredFields();//獲取所有屬性
Field[] children = subclass.getClass().getSuperclass().getDeclaredFields();//獲取父類所有屬性
try {
for (Field fieldParent : parents){
fieldParent.setAccessible(true);
String nameParent = fieldParent.getName(); //獲取屬性的名字
Object valueParent = fieldParent.get(parent);//獲取屬性值
for (Field fieldChild : children){
fieldChild.setAccessible(true);
String nameChild = fieldChild.getName(); //獲取屬性的名字
Object valueChild= fieldChild.get(subclass);
if (nameChild.equals(nameParent)){
fieldChild.set(subclass,valueParent);
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return subclass;
}
/**
* @Author zx
* @Description 通過json
* @Date 2019/12/19 9:21
* @Param [parent, subclass]
**/
public static Object jsonParentSubclass(Object parent,Object subclass){
String op = JSONObject.toJSONString(parent);
return JSONObject.parseObject(op,subclass.getClass());
}
}
3、測試
Document document = new Document();
document.setDocumentCd("11111111");
document.setDocumentTitle("title");
System.out.println("1:"+new Date().getTime());
DocumentView documentView = (DocumentView) StrongParentSubclass.parentSubclass(document,new DocumentView());
System.out.println("2:"+new Date().getTime()+"--"+documentView.getDocumentCd()+"--"+documentView.getDocumentTitle());
System.out.println("1:"+new Date().getTime());
DocumentView documentView1 = (DocumentView) StrongParentSubclass.jsonParentSubclass(document,new DocumentView());
System.out.println("3:"+new Date().getTime()+"--"+documentView1.getDocumentCd()+"--"+documentView.getDocumentTitle());
System.out.println(documentView);
結果:
1:1576720028591
2:1576720028592--11111111--title
1:1576720028592
3:1576720028788--11111111--title
com.power.xsj13000x.dto.v2.DocumentView@5ba23b66
根據結果發現,反射循環賦值時間更快一點。