先上代码,可直接食用
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);
结果:
1:1576720028591 2:1576720028592--11111111--title 1:1576720028592 3:1576720028788--11111111--title com.power.xsj13000x.dto.v2.DocumentView@5ba23b66
根据结果发现,反射循环赋值时间更快一点。