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; //設置訪問權限 f1.setAccessible(true); Object value = f1.get(class1); for (Field f2 : fields2) { if(f1.getName().equals(f2.getName())){ //設置訪問權限 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); } } } } /** * * 執行某個Field的getField方法 * @param clazz 類 * @param fieldName 類的屬性名稱 * @param args 參數,默認為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 ''; } } /** * * 執行某個Field的setField方法 * @param clazz 類 * @param fieldName 類的屬性名稱 * @param args 參數,默認為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轉換為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; }}
二、調用工具類
ClassReflection.reflectionAttr(class1, class2);
三、賦值完成
注意:
1、id不賦值,主要給數據庫兩張表賦值,比如當前表和歷史表,把當前表的相同字段的值賦值給歷史表
2、簡單版設置private修飾的字段可以被訪問
補充知識:利用java反射原理給實體類注值
寫一個通用java注值的方法,使用泛型T,將其封裝在DbHelp中(相信DbHelper不用我解釋是什么),使dao調用直接獲取所需要的對象,也正應用了我們java面向對象的思想
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方法對應數據庫字段的值 String pt=m.getParameterTypes()[0].toString();//取到set方法的參數類型 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反射機制給實體類相同字段自動賦值實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: