栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java反射机制给实体类相同字段自动赋值实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 {
   
   
  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 {
   
   
   
  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); 
 } 
      } 
    } 
  } 
   
   
  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 ""; 
    } 
  }    
   
  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 getBean(String sql,Class 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反射机制给实体类相同字段自动赋值实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132452.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号