溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java通過反射給實體類賦值的案例分析

發(fā)布時間:2020-08-21 10:24:24 來源:億速云 閱讀:356 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Java通過反射給實體類賦值的案例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

表單提交這個方法是挺方便的,但在java來說就顯得有些麻煩了,

怎么個麻煩呢,就是當(dāng)你字段多的時候,你就得一個一個的獲取其對應(yīng)的值,這樣代碼量就多了起來,其代碼量不說,維護(hù)也是一個問題。

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

這樣就會得到一個有值的實體類對象

下面是代碼示例

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請求的數(shù)據(jù)放到j(luò)ava對象中
	 */
	public static <T> T getSingleRequest(HttpServletRequest request, Class<T> obj) {
		//創(chuàng)建實例
		T instance = null;
		try {
//獲取類中聲明的所有字段
			Field[] fields = obj.getDeclaredFields();
//創(chuàng)建新的實例對象
			instance = obj.newInstance();
//利用循環(huán)
			for (int i = 0; i < fields.length; i++) {
//獲取字段的名稱
				String name = fields[i].getName();
//把序列化id篩選掉
				if (name.equals("serialVersionUID")) {
					continue;
				}
//獲取字段的類型
				Class<&#63;> type = obj.getDeclaredField(name).getType();
				
				// 首字母大寫
				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)) {
					// 首字母小寫
					String small = name.substring(0, 1).toLowerCase()
							+ name.substring(1);
					str = request.getParameter(small);
				}
//通過setter方法賦值給對應(yīng)的成員變量
				if (str != null && !"".equals(str)) {
					// ---判斷讀取數(shù)據(jù)的類型
					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();
		}
//返回實體類對象
		return instance;
	}
}

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

項目中需要過濾前面表單頁面中傳過來的實體類的中的String類型變量的前后空格過濾,由于前幾天看過一個其他技術(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中變量類型為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,非的話這過濾前后空格
          if(methodValue != null && !"".equals(methodValue)){
            //獲取set方法名
            String setMethodName = "set"+fields[j].getName().substring(0, 1).toUpperCase()
                +fields[j].getName().replaceFirst("\\w", "");
            //得到get方法的Method對象,帶參數(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();
        }
      }
    }
  }

親自上面試用是好使的

下面還有一套,通過request,和實體類來封裝本人還未實驗,以后有機(jī)會再試試

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

關(guān)于Java通過反射給實體類賦值的案例分析就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI