java反射機制給實體類相同字段自動賦值實例
一、封裝一個工具類
1、簡易版
package net.aexit.construct.acceptance.websky.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ClassReflection { /** * @param class1 用于賦值的實體類 * @param class2 需要待賦值的實體類 * 描述:反射實體類賦值 */ public static void reflectionAttr(Object class1,Object class2) throws Exception{ Class clazz1 = class1.getClass(); Class clazz2 = class2.getClass(); // 獲取兩個實體類的所有屬性 Field[] fields1 = clazz1.getDeclaredFields(); Field[] fields2 = clazz2.getDeclaredFields(); // 遍歷class1Bean,獲取逐個屬性值,然后遍歷class2Bean查找是否有相同的屬性,如有相同則賦值 for (Field f1 : fields1) { if(f1.getName().equals("id")) continue; //設(shè)置訪問權(quán)限 f1.setAccessible(true); Object value = f1.get(class1); for (Field f2 : fields2) { if(f1.getName().equals(f2.getName())){ //設(shè)置訪問權(quán)限 f2.setAccessible(true); f2.set(class2,value); } } } } }
2、復雜版
package net.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ClassReflection { /** * @param class1 用于賦值的實體類 * @param class2 需要待賦值的實體類 * 描述:反射實體類賦值 */ public static void reflectionAttr(Object class1,Object class2) throws Exception{ Class clazz1 = Class.forName(class1.getClass().getName()); Class clazz2 = Class.forName(class2.getClass().getName()); // 獲取兩個實體類的所有屬性 Field[] fields1 = clazz1.getDeclaredFields(); Field[] fields2 = clazz2.getDeclaredFields(); ClassReflection cr = new ClassReflection(); // 遍歷class1Bean,獲取逐個屬性值,然后遍歷class2Bean查找是否有相同的屬性,如有相同則賦值 for (Field f1 : fields1) { if(f1.getName().equals("id")) continue; Object value = cr.invokeGetMethod(class1 ,f1.getName(),null); for (Field f2 : fields2) { if(f1.getName().equals(f2.getName())){ Object[] obj = new Object[1]; obj[0] = value; cr.invokeSetMethod(class2, f2.getName(), obj); } } } } /** * * 執(zhí)行某個Field的getField方法 * @param clazz 類 * @param fieldName 類的屬性名稱 * @param args 參數(shù),默認為null * @return */ public Object invokeGetMethod(Object clazz, String fieldName, Object[] args) { String methodName = fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1); Method method = null; try { method = Class.forName(clazz.getClass().getName()).getDeclaredMethod("get" + methodName); return method.invoke(clazz); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * * 執(zhí)行某個Field的setField方法 * @param clazz 類 * @param fieldName 類的屬性名稱 * @param args 參數(shù),默認為null * @return */ public Object invokeSetMethod(Object clazz, String fieldName, Object[] args) { String methodName = fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1); Method method = null; try { Class[] parameterTypes = new Class[1]; Class c = Class.forName(clazz.getClass().getName()); Field field = c.getDeclaredField(fieldName); parameterTypes[0] = field.getType(); method = c.getDeclaredMethod("set" + methodName,parameterTypes); return method.invoke(clazz,args); } catch (Exception e) { e.printStackTrace(); return ""; } } //map轉(zhuǎn)換為json字符串 public static String hashMapToJson(HashMap map) { String string = "{"; for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry e = (Map.Entry) it.next(); string += "'" + e.getKey() + "':"; string += "'" + e.getValue() + "',"; } string = string.substring(0, string.lastIndexOf(",")); string += "}"; return string; } }
二、調(diào)用工具類
ClassReflection.reflectionAttr(class1, class2);
三、賦值完成
注意:
1、id不賦值,主要給數(shù)據(jù)庫兩張表賦值,比如當前表和歷史表,把當前表的相同字段的值賦值給歷史表
2、簡單版設(shè)置private修飾的字段可以被訪問
補充知識:利用java反射原理給實體類注值
寫一個通用java注值的方法,使用泛型T,將其封裝在DbHelp中(相信DbHelper不用我解釋是什么),使dao調(diào)用直接獲取所需要的對象,也正應(yīng)用了我們java面向?qū)ο蟮乃枷?/p>
public static<T> T getBean(String sql,Class<T> clazz){ Method[] ms=clazz.getDeclaredMethods(); T t=null; try { t=clazz.newInstance(); for (Method m : ms) { String mn=m.getName(); if(mn.startsWith("set")){ Object obj=map.get((mn.replace("set", "").toUpperCase()));//取到set方法對應(yīng)數(shù)據(jù)庫字段的值 String pt=m.getParameterTypes()[0].toString();//取到set方法的參數(shù)類型 if(obj!=null){ if(pt.endsWith("int")||pt.endsWith("Integer")){ m.invoke(t, ((BigDecimal)obj).intValue()); }else if(pt.endsWith("Double")||pt.endsWith("double")){ m.invoke(t, ((BigDecimal)obj).doubleValue()); }else if(pt.endsWith("Date")){ m.invoke(t, (Timestamp)obj); }else { m.invoke(t, obj); } } } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return t; }
以上這篇java反射機制給實體類相同字段自動賦值實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用SpringBoot進行身份驗證和授權(quán)的示例詳解
在廣闊的 Web 開發(fā)世界中,身份驗證是每個數(shù)字領(lǐng)域的守護者,在本教程中,我們將了解如何以本機方式保護、驗證和授權(quán) Spring-Boot 應(yīng)用程序的用戶,并遵循框架的良好實踐,希望對大家有所幫助2023-11-11使用jekins自動構(gòu)建部署java maven項目的方法步驟
這篇文章主要介紹了使用jekins自動構(gòu)建部署java maven項目的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01Spring Boot Actuator端點相關(guān)原理解析
這篇文章主要介紹了Spring Boot Actuator端點相關(guān)原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式
Spring Cloud OAuth2 生成access token的請求/oauth/token的返回內(nèi)容就需要自定義,本文就詳細介紹一下,感興趣的可以了解一下2021-07-07Java動態(tài)初始化數(shù)組,元素默認值規(guī)則詳解
動態(tài)初始化數(shù)組涉及先定義數(shù)組長度,后填充具體數(shù)據(jù),適用于數(shù)據(jù)量已知但具體值未定的情況,這種初始化方式允許程序運行過程中賦值,并會根據(jù)數(shù)據(jù)類型設(shè)定默認值,如整型為0,字符串為null,動態(tài)初始化與靜態(tài)初始化格式不能混用2024-10-10