最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java 通過(guò)反射給實(shí)體類(lèi)賦值操作

 更新時(shí)間:2020年08月20日 10:47:29   作者:IT 練習(xí)生  
這篇文章主要介紹了Java 通過(guò)反射給實(shí)體類(lèi)賦值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

表單提交這個(gè)方法是挺方便的,但在java來(lái)說(shuō)就顯得有些麻煩了,

怎么個(gè)麻煩呢,就是當(dāng)你字段多的時(shí)候,你就得一個(gè)一個(gè)的獲取其對(duì)應(yīng)的值,這樣代碼量就多了起來(lái),其代碼量不說(shuō),維護(hù)也是一個(gè)問(wèn)題。

所以就有了這樣一個(gè)類(lèi),只需把request和實(shí)體類(lèi)對(duì)象傳進(jìn)去就行了,

這樣就會(huì)得到一個(gè)有值的實(shí)體類(lèi)對(duì)象

下面是代碼示例

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
 
import javax.servlet.http.HttpServletRequest;
 
public class RequestHelper {
	/**
	 * 把request請(qǐng)求的數(shù)據(jù)放到j(luò)ava對(duì)象中
	 */
	public static <T> T getSingleRequest(HttpServletRequest request, Class<T> obj) {
		//創(chuàng)建實(shí)例
		T instance = null;
		try {
//獲取類(lèi)中聲明的所有字段
			Field[] fields = obj.getDeclaredFields();
//創(chuàng)建新的實(shí)例對(duì)象
			instance = obj.newInstance();
//利用循環(huán)
			for (int i = 0; i < fields.length; i++) {
//獲取字段的名稱
				String name = fields[i].getName();
//把序列化id篩選掉
				if (name.equals("serialVersionUID")) {
					continue;
				}
//獲取字段的類(lèi)型
				Class<?> type = obj.getDeclaredField(name).getType();
				
				// 首字母大寫(xiě)
				String replace = name.substring(0, 1).toUpperCase()
						+ name.substring(1);
//獲得setter方法
				Method setMethod = obj.getMethod("set" + replace, type);
//獲取到form表單的所有值
				String str = request.getParameter(replace);
				if (str == null || "".equals(str)) {
					// 首字母小寫(xiě)
					String small = name.substring(0, 1).toLowerCase()
							+ name.substring(1);
					str = request.getParameter(small);
				}
//通過(guò)setter方法賦值給對(duì)應(yīng)的成員變量
				if (str != null && !"".equals(str)) {
					// ---判斷讀取數(shù)據(jù)的類(lèi)型
					if (type.isAssignableFrom(String.class)) {
						setMethod.invoke(instance, str);
					} else if (type.isAssignableFrom(int.class)
							|| type.isAssignableFrom(Integer.class)) {
						setMethod.invoke(instance, Integer.parseInt(str));
					} else if (type.isAssignableFrom(Double.class)
							|| type.isAssignableFrom(double.class)) {
						setMethod.invoke(instance, Double.parseDouble(str));
					} else if (type.isAssignableFrom(Boolean.class)
							|| type.isAssignableFrom(boolean.class)) {
						setMethod.invoke(instance, Boolean.parseBoolean(str));
					} else if (type.isAssignableFrom(Date.class)) {
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						setMethod.invoke(instance, dateFormat.parse(str));
					} else if (type.isAssignableFrom(Timestamp.class)) {
						SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						setMethod.invoke(instance, new Timestamp(dateFormat.parse(str).getTime()));
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//返回實(shí)體類(lèi)對(duì)象
		return instance;
	}
}

補(bǔ)充知識(shí):java反射對(duì)實(shí)體類(lèi)取值和賦值,可以寫(xiě)成通過(guò)實(shí)體類(lèi)獲取其他元素的數(shù)據(jù),很方便哦~~~

項(xiàng)目中需要過(guò)濾前面表單頁(yè)面中傳過(guò)來(lái)的實(shí)體類(lèi)的中的String類(lèi)型變量的前后空格過(guò)濾,由于前幾天看過(guò)一個(gè)其他技術(shù)博客的的java反射講解,非常受益。于是,哈哈哈

public static <T> void modelTrim(T model){
    Class<T> clazz = (Class<T>) model.getClass();
    //獲取所有的bean中所有的成員變量
    Field[] fields = clazz.getDeclaredFields();
    for(int j=0;j<fields.length;j++){
      //獲取所有的bean中變量類(lèi)型為String的變量
      if("String".equals(fields[j].getType().getSimpleName())){
        try {
          //獲取get方法名
          String methodName = "get"+fields[j].getName().substring(0, 1).toUpperCase()
              +fields[j].getName().replaceFirst("\\w", "");
          Method getMethod = clazz.getDeclaredMethod(methodName);
          //打破封裝
          getMethod.setAccessible(true);
          //得到該方法的值
          Object methodValue = getMethod.invoke(model);
          //判斷值是否為空或者為null,非的話這過(guò)濾前后空格
          if(methodValue != null && !"".equals(methodValue)){
            //獲取set方法名
            String setMethodName = "set"+fields[j].getName().substring(0, 1).toUpperCase()
                +fields[j].getName().replaceFirst("\\w", "");
            //得到get方法的Method對(duì)象,帶參數(shù)
            Method setMethod = clazz.getDeclaredMethod(setMethodName,fields[j].getType());
            setMethod.setAccessible(true);
            //賦值
            setMethod.invoke(model, (Object)String.valueOf(methodValue).trim());
          }
        } catch (NoSuchMethodException e) {
          e.printStackTrace();
        } catch (SecurityException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (IllegalArgumentException e) {
          e.printStackTrace();
        } catch (InvocationTargetException e) {
          e.printStackTrace();
        }
      }
    }
  }

親自上面試用是好使的

下面還有一套,通過(guò)request,和實(shí)體類(lèi)來(lái)封裝本人還未實(shí)驗(yàn),以后有機(jī)會(huì)再試試

/**
   * 保存數(shù)據(jù) 
   *@param request
   *@param dto
   *@throws Exception
   */
  public static void setDTOValue(HttpServletRequest request, Object dto) throws Exception {
    if ((dto == null) || (request == null))
      return;
    //得到類(lèi)中所有的方法 基本上都是set和get方法
    Method[] methods = dto.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
      try {
        //方法名
        String methodName = methods[i].getName();
        //方法參數(shù)的類(lèi)型
        Class[] type = methods[i].getParameterTypes();
        //當(dāng)時(shí)set方法時(shí),判斷依據(jù):setXxxx類(lèi)型
        if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) {
          //將set后面的大寫(xiě)字母轉(zhuǎn)成小寫(xiě)并截取出來(lái)
          String name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
          Object objValue = getBindValue(request, name, type[0]);
          if (objValue != null) {
            Object[] value = { objValue };
            invokeMothod(dto, methodName, type, value);
          }
        }
      } catch (Exception ex) {
        throw ex;
      }
    }
  }

以上這篇Java 通過(guò)反射給實(shí)體類(lèi)賦值操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 解決RedisTemplate存儲(chǔ)至緩存數(shù)據(jù)出現(xiàn)亂碼的情況

    解決RedisTemplate存儲(chǔ)至緩存數(shù)據(jù)出現(xiàn)亂碼的情況

    這篇文章主要介紹了解決RedisTemplate存儲(chǔ)至緩存數(shù)據(jù)出現(xiàn)亂碼的情況,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-03-03
  • Mybatis條件if test如何使用枚舉值

    Mybatis條件if test如何使用枚舉值

    這篇文章主要介紹了Mybatis條件if test如何使用枚舉值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Feign調(diào)用服務(wù)各種坑的處理方案

    Feign調(diào)用服務(wù)各種坑的處理方案

    這篇文章主要介紹了Feign調(diào)用服務(wù)各種坑的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 關(guān)于struts2中Action名字的大小寫(xiě)問(wèn)題淺談

    關(guān)于struts2中Action名字的大小寫(xiě)問(wèn)題淺談

    這篇文章主要給大家介紹了關(guān)于struts2中Action名字大小寫(xiě)問(wèn)題的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。
    2017-06-06
  • 淺析Mybatis Plus和Mybatis的區(qū)別

    淺析Mybatis Plus和Mybatis的區(qū)別

    這篇文章主要介紹了Mybatis Plus和Mybatis的區(qū)別,需要的朋友可以參考下
    2020-08-08
  • Mybatis通用Mapper(tk.mybatis)的使用

    Mybatis通用Mapper(tk.mybatis)的使用

    本文主要介紹了Mybatis通用Mapper(tk.mybatis)的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • 使用Spring靜態(tài)注入實(shí)現(xiàn)讀取配置工具類(lèi)新方式

    使用Spring靜態(tài)注入實(shí)現(xiàn)讀取配置工具類(lèi)新方式

    這篇文章主要介紹了使用Spring靜態(tài)注入實(shí)現(xiàn)讀取配置工具類(lèi)新方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)session管理實(shí)例

    Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)session管理實(shí)例

    本篇文章主要介紹了Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)session管理實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • java常用的加密解決方案分享

    java常用的加密解決方案分享

    這篇文章全面介紹了Java中加解密技術(shù)的應(yīng)用,包括哈希函數(shù)、對(duì)稱加密、非對(duì)稱加密、消息認(rèn)證碼和數(shù)字簽名等,它詳細(xì)解釋了每種技術(shù)的工作原理,并提供了相應(yīng)的Java代碼示例,文章還強(qiáng)調(diào)了密鑰管理的重要性,并提出了在實(shí)際應(yīng)用中遵循的最佳實(shí)踐
    2025-01-01
  • 使用自定義注解實(shí)現(xiàn)redisson分布式鎖

    使用自定義注解實(shí)現(xiàn)redisson分布式鎖

    這篇文章主要介紹了使用自定義注解實(shí)現(xiàn)redisson分布式鎖,具有很好的參考價(jià)值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02

最新評(píng)論

特克斯县| 闻喜县| 黎川县| 昂仁县| 晋中市| 高雄市| 独山县| 铜川市| 温泉县| 沿河| 阿瓦提县| 临漳县| 安顺市| 闽清县| 门源| 大渡口区| 屏东市| 扶绥县| 穆棱市| 成都市| 财经| 金乡县| 龙井市| 迁安市| 孟津县| 祥云县| 凌云县| 礼泉县| 读书| 安福县| 阿勒泰市| 锡林浩特市| 南通市| 梅州市| 建水县| 锦州市| 保德县| 林口县| 吕梁市| 兰坪| 中卫市|