java反射机制是什么
反射机制是在运行状态中,可以知道任何一个类的属性和方法,并且调用类的属性和方法;
反射机制能够做什么
1、判断运行对象的所属类
2、构造任意一个类的对象
3、获取任意一个类的属性和方法
4、调用任意属性和方法
5、生成动态代理
利用反射将结果集封装成为对象或者集合(实测可用)
package coral.base.util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import wfc.service.database.RecordSet; public class ReflectUtils { /** * 将一个map集合封装成为bean对象 * * @param param * @param clazz * @return */ public staticT MapToBean(Map param, Class> clazz) { Object value = null; Class[] paramTypes = new Class[1]; Object obj = null; try { obj = clazz.newInstance(); // 获取类的属性 Field[] declaredFields = clazz.getDeclaredFields(); // 获取父类或接口的公有属性 Field[] superFields = clazz.getSuperclass().getFields(); List list = new ArrayList (); if (declaredFields != null) { list.add(declaredFields); } if (superFields != null) { list.add(superFields); } for (Field[] fields : list) { for (Field field : fields) { String fieldName = field.getName(); // 获取属性对应的值ֵ value = param.get(fieldName); // 把值设置进入对象属性中 这里可能是有属性但是没有相应的set方法,所以要做异常处理 try { PropertyDescriptor pd = new PropertyDescriptor( fieldName, clazz); Method method = pd.getWriteMethod(); method.invoke(obj, new Object[] { value }); } catch (Exception e1) { } } } } catch (Exception e1) { } return (T) obj; } /** * 获取类的所有属性,包括父类和接口 * @param clazz * @return */ public static List getBeanFields(Class> clazz) { List list = new ArrayList (); Field[] declaredFields = clazz.getDeclaredFields(); Field[] superFields = clazz.getSuperclass().getFields(); if (declaredFields != null) { list.add(declaredFields); } if (superFields != null) { list.add(superFields); } return list; } /** * 从结果集中获取出值 * @param fieldName * @param rs * @return */ public static Object getFieldValue(String fieldName, ResultSet rs) { Object value = null; try { //捕获值不存在的异常 value = rs.getObject(fieldName); return value; } catch (SQLException e) { //oracle数据库的列都是大写,所以才查找一次 fieldName = fieldName.toLowerCase(); try { value = rs.getObject(fieldName); return value; } catch (SQLException e1) { //结果集中没有对应的值,返回为空 return null; } } } /** * 方法重载, * @param fieldName * @param rs 这个是封装过的结果集 * @return */ public static Object getFieldValue(String fieldName, RecordSet rs) { Object value = null; value = rs.getObject(fieldName); return value; } /** * 方法重载 * @param rs 封装过的结果集 * @param clazz * @return */ public static T RSToBean(RecordSet rs, Class> clazz) { Object obj = null; List list = getBeanFields(clazz); try { obj = clazz.newInstance(); for (Field[] fields : list) { for (Field field : fields) { String fieldName = field.getName(); // String fieldName = field.getName();ֵ Object value = getFieldValue(fieldName, rs); try { PropertyDescriptor pd = new PropertyDescriptor( fieldName, clazz); Method method = pd.getWriteMethod(); method.invoke(obj, new Object[] { value }); } catch (Exception e1) { } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return (T) obj; } /** * 把结果集封装成为bean对象 * @param rs * @param clazz * @return */ public static T RSToBean(ResultSet rs, Class> clazz) { Object obj = null; List list = getBeanFields(clazz); try { while (rs.next()) { obj = clazz.newInstance(); for (Field[] fields : list) { for (Field field : fields) { String fieldName = field.getName(); // String fieldName = field.getName();ֵ Object value = getFieldValue(fieldName, rs); PropertyDescriptor pd = new PropertyDescriptor( fieldName, clazz); Method method = pd.getWriteMethod(); method.invoke(obj, new Object[] { value }); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return (T) obj; } /** * 把结果集封装成为List * * @param rs * @param clazz * @return */ public static List RsToList(ResultSet rs, Class> clazz) { ArrayList objList = new ArrayList (); // 获取所有的属性 List list = getBeanFields(clazz); try { while (rs.next()) { // 定义临时变量 Object tempObeject = clazz.newInstance(); // 添加到属性中 for (Field[] fields : list) { for (Field field : fields) { String fieldName = field.getName(); // 获取属性值ֵ Object value = getFieldValue(fieldName, rs); PropertyDescriptor pd = new PropertyDescriptor( fieldName, clazz); Method method = pd.getWriteMethod(); method.invoke(tempObeject, new Object[] { value }); } } objList.add((T) tempObeject); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return objList; } }
补充知识:java反射自动封装值到实体类
1.工具类
package com.util; import com.entity.Student; import javax.servlet.ServletRequest; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Enumeration; /** * Created by wq on 2017/8/30. */ public class BeanOperateTools { /* 利用反射进行所以请求参数的设置,要求参数名与属性名一致 */ /** * * @param obj * @param req * @param datePatern 将字符串变为日期时间格式化的字符串 * @throws Exception */ public static void setValue(Object obj, ServletRequest req,String datePatern) throws Exception {//设置属性的内容 { System.out.println("进了setValue方法....."); //取得class对象 Class> cls = obj.getClass(); //取得输入的全部参数名称 Enumerationenu = req.getParameterNames(); //循环输入的全部参数名称 while (enu.hasMoreElements()) { String paramName = enu.nextElement();//取得参数名称 String paramValue = req.getParameter(paramName); //取得属性的类型是为了取得参数的类型,以确定method方法和是否转型 Field field = cls.getDeclaredField(paramName); //取得指定名称的属性 (实体类里面 //取得指定的操作方法,以满足反射调用 Method method = cls.getMethod("set"+StringTools.initcap(paramName),field.getType()); //根据类型进行数据的转换,同时调用setter设置数据 //取得类型 String fieldType=field.getType().getSimpleName(); if ("string".equalsIgnoreCase(fieldType)) { method.invoke(obj,paramValue); }else if ("integer".equalsIgnoreCase(fieldType)||"int".equalsIgnoreCase(fieldType)){ method.invoke(obj,Integer.parseInt(paramValue)); }else if ("double".equalsIgnoreCase(fieldType)){ method.invoke(obj,Double.parseDouble(paramValue)); }else if ("date".equalsIgnoreCase(fieldType)){ method.invoke(obj,new SimpleDateFormat(datePatern).parse(paramValue)); } } } } }
2.servlet中调用此方法
package com.servlet; import com.entity.Student; import com.sun.xml.internal.bind.v2.runtime.reflect.opt.FieldAccessor_Double; import com.util.BeanOperateTools; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Enumeration; /** * Created by wq on 2017/8/22. */ @WebServlet(name = "studentServlet", urlPatterns = {"/StudentServlet"}) public class StudentServlet extends HttpServlet { //private Student stu = new Student(); private Student student=new Student(); public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } -------此处模仿依赖注入 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); try { BeanOperateTools.setValue(this.getStudent(),req,"yyyy-MM-dd"); } catch (Exception e) { e.printStackTrace(); } req.setAttribute("student",this.student); req.getRequestDispatcher("student_insert_do.jsp").forward(req,resp); // Class> cls= this.stu.getClass(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } public String initcap(String str) {//首字母大写 return str.substring(0, 1).toUpperCase().concat(str.substring(1).toLowerCase()); } }
3.新增学生的jsp页面
<%-- Created by IntelliJ IDEA. User: wq Date: 2017/8/21 Time: 23:25 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %>Title
4。展示学生的信息的页面
<%-- Created by IntelliJ IDEA. User: wq Date: 2017/8/21 Time: 23:25 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %>Title 姓名:${student.name}
年龄:${student.age}
成绩:${student.score}
以上这篇使用java反射将结果集封装成为对象和对象集合操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。