先上代碼,可直接食用
package com.utils; 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()); } }
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);
結果:java
1:1576720028591 2:1576720028592--11111111--title 1:1576720028592 3:1576720028788--11111111--title com.power.xsj13000x.dto.v2.DocumentView@5ba23b66
根據結果發現,反射循環賦值時間更快一點。spring