这篇文章将为大家详细讲解有关Java通过反射给实体类赋值的案例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
表单提交这个方法是挺方便的,但在java来说就显得有些麻烦了,
怎么个麻烦呢,就是当你字段多的时候,你就得一个一个的获取其对应的值,这样代码量就多了起来,其代码量不说,维护也是一个问题。
所以就有了这样一个类,只需把request和实体类对象传进去就行了,
这样就会得到一个有值的实体类对象
下面是代码示例
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请求的数据放到java对象中
*/
public static <T> T getSingleRequest(HttpServletRequest request, Class<T> obj) {
//创建实例
T instance = null;
try {
//获取类中声明的所有字段
Field[] fields = obj.getDeclaredFields();
//创建新的实例对象
instance = obj.newInstance();
//利用循环
for (int i = 0; i < fields.length; i++) {
//获取字段的名称
String name = fields[i].getName();
//把序列化id筛选掉
if (name.equals("serialVersionUID")) {
continue;
}
//获取字段的类型
Class<?> 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方法赋值给对应的成员变量
if (str != null && !"".equals(str)) {
// ---判断读取数据的类型
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;
}
}
补充知识:java反射对实体类取值和赋值,可以写成通过实体类获取其他元素的数据,很方便哦~~~
项目中需要过滤前面表单页面中传过来的实体类的中的String类型变量的前后空格过滤,由于前几天看过一个其他技术博客的的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对象,带参数
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,和实体类来封装本人还未实验,以后有机会再试试
/**
* 保存数据
*@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();
//方法参数的类型
Class[] type = methods[i].getParameterTypes();
//当时set方法时,判断依据:setXxxx类型
if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) {
//将set后面的大写字母转成小写并截取出来
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通过反射给实体类赋值的案例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。