Java 通過(guò)反射給實(shí)體類(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++) {
//獲取字段的名稱(chēng)
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,非的話(huà)這過(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è)參考,也希望大家多多支持腳本之家。
- Java如何通過(guò)反射方式生成數(shù)據(jù)庫(kù)實(shí)體類(lèi)
- Java反射機(jī)制,如何將一個(gè)實(shí)體類(lèi)所有字段賦值為null
- java 實(shí)現(xiàn)反射 json動(dòng)態(tài)轉(zhuǎn)實(shí)體類(lèi)--fastjson
- 利用JAVA反射,讀取數(shù)據(jù)庫(kù)表名,自動(dòng)生成對(duì)應(yīng)實(shí)體類(lèi)的操作
- java反射機(jī)制給實(shí)體類(lèi)相同字段自動(dòng)賦值實(shí)例
- java反射遍歷實(shí)體類(lèi)屬性和類(lèi)型,并賦值和獲取值的簡(jiǎn)單方法
- Java如何通過(guò)反射取實(shí)體類(lèi)字段取值
相關(guān)文章
解決RedisTemplate存儲(chǔ)至緩存數(shù)據(jù)出現(xiàn)亂碼的情況
這篇文章主要介紹了解決RedisTemplate存儲(chǔ)至緩存數(shù)據(jù)出現(xiàn)亂碼的情況,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
關(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通用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)新方式,具有很好的參考價(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í)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
使用自定義注解實(shí)現(xiàn)redisson分布式鎖
這篇文章主要介紹了使用自定義注解實(shí)現(xiàn)redisson分布式鎖,具有很好的參考價(jià)值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

