Java反射 - 简单的给Bean赋值和取值
由于项目的实际需要,所以利用java反射原理写了一个简单给bean赋值和取值通用的类,在此记录下方便自己日后用到,也为需要的兄弟提供个参考例子。
工具类BeanRefUtil:
- package com.test;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Locale;
- import java.util.Map;
- /**
- * java bean 反射的方法
- */
- public class BeanRefUtil {
- /**
- * 取Bean的属性和值对应关系的MAP
- * @param bean
- * @return Map
- */
- public static Map<String, String> getFieldValueMap(Object bean) {
- Class<?> cls = bean.getClass();
- Map<String, String> valueMap = new HashMap<String, String>();
- // 取出bean里的所有方法
- Method[] methods = cls.getDeclaredMethods();
- Field[] fields = cls.getDeclaredFields();
- for (Field field : fields) {
- try {
- String fieldType = field.getType().getSimpleName();
- String fieldGetName = parGetName(field.getName());
- if (!checkGetMet(methods, fieldGetName)) {
- continue;
- }
- Method fieldGetMet = cls
- .getMethod(fieldGetName, new Class[] {});
- Object fieldVal = fieldGetMet.invoke(bean, new Object[] {});
- String result = null;
- if ("Date".equals(fieldType)) {
- result = fmtDate((Date) fieldVal);
- } else {
- if (null != fieldVal) {
- result = String.valueOf(fieldVal);
- }
- }
- valueMap.put(field.getName(), result);
- } catch (Exception e) {
- continue;
- }
- }
- return valueMap;
- }
- /**
- * set属性的值到Bean
- * @param bean
- * @param valMap
- */
- public static void setFieldValue(Object bean, Map<String, String> valMap) {
- Class<?> cls = bean.getClass();
- // 取出bean里的所有方法
- Method[] methods = cls.getDeclaredMethods();
- Field[] fields = cls.getDeclaredFields();
- for (Field field : fields) {
- try {
- String fieldSetName = parSetName(field.getName());
- if (!checkSetMet(methods, fieldSetName)) {
- continue;
- }
- Method fieldSetMet = cls.getMethod(fieldSetName, field
- .getType());
- String value = valMap.get(field.getName());
- if (null != value && !"".equals(value)) {
- String fieldType = field.getType().getSimpleName();
- if ("String".equals(fieldType)) {
- fieldSetMet.invoke(bean, value);
- } else if ("Date".equals(fieldType)) {
- Date temp = parseDate(value);
- fieldSetMet.invoke(bean, temp);
- } else if ("Integer".equals(fieldType)
- || "int".equals(fieldType)) {
- Integer intval = Integer.parseInt(value);
- fieldSetMet.invoke(bean, intval);
- } else if ("Long".equalsIgnoreCase(fieldType)) {
- Long temp = Long.parseLong(value);
- fieldSetMet.invoke(bean, temp);
- } else if ("Double".equalsIgnoreCase(fieldType)) {
- Double temp = Double.parseDouble(value);
- fieldSetMet.invoke(bean, temp);
- } else if ("Boolean".equalsIgnoreCase(fieldType)) {
- Boolean temp = Boolean.parseBoolean(value);
- fieldSetMet.invoke(bean, temp);
- } else {
- System.out.println("not supper type" + fieldType);
- }
- }
- } catch (Exception e) {
- continue;
- }
- }
- }
- /**
- * 格式化string为Date
- * @param datestr
- * @return date
- */
- public static Date parseDate(String datestr) {
- if (null == datestr || "".equals(datestr)) {
- return null;
- }
- try {
- String fmtstr = null;
- if (datestr.indexOf(':') > 0) {
- fmtstr = "yyyy-MM-dd HH:mm:ss";
- } else {
- fmtstr = "yyyy-MM-dd";
- }
- SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK);
- return sdf.parse(datestr);
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 日期转化为String
- * @param date
- * @return date string
- */
- public static String fmtDate(Date date) {
- if (null == date) {
- return null;
- }
- try {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
- Locale.US);
- return sdf.format(date);
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 判断是否存在某属性的 set方法
- * @param methods
- * @param fieldSetMet
- * @return boolean
- */
- public static boolean checkSetMet(Method[] methods, String fieldSetMet) {
- for (Method met : methods) {
- if (fieldSetMet.equals(met.getName())) {
- return true;
- }
- }
- return false;
- }
- /**
- * 判断是否存在某属性的 get方法
- * @param methods
- * @param fieldGetMet
- * @return boolean
- */
- public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
- for (Method met : methods) {
- if (fieldGetMet.equals(met.getName())) {
- return true;
- }
- }
- return false;
- }
- /**
- * 拼接某属性的 get方法
- * @param fieldName
- * @return String
- */
- public static String parGetName(String fieldName) {
- if (null == fieldName || "".equals(fieldName)) {
- return null;
- }
- return "get" + fieldName.substring(0, 1).toUpperCase()
- + fieldName.substring(1);
- }
- /**
- * 拼接在某属性的 set方法
- * @param fieldName
- * @return String
- */
- public static String parSetName(String fieldName) {
- if (null == fieldName || "".equals(fieldName)) {
- return null;
- }
- return "set" + fieldName.substring(0, 1).toUpperCase()
- + fieldName.substring(1);
- }
- }
Java反射 - 简单的给Bean赋值和取值的更多相关文章
- js实现hashtable的赋值、取值、遍历
哈希表(Hashtable)这个概率应该是#c里面的概念,用来赋值.取值.遍历.排序操作提高效率.想起这个东西其实使我们以前经常遇到这样的面试题,一个很大的数组可能有100000个,如何快速知道它里面 ...
- 关于ligerform中select与text的赋值与取值
如有下ligerform表单: var formData = [ { display: "区域", name: "QYYJ", newline: true, l ...
- Jquery实现数据双向绑定(赋值和取值),类似AngularJS
<!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...
- 实用ExtJS教程100例-011:ExtJS Form 使用JSON数据赋值和取值
上一节中我们演示了ExtJS Form的异步加载和提交数据,本节中我们将演示如何使用JSON数据为ExtJS Form中的字段赋值和取值. 系列ExtJS教程持续更新中,点击查看>>最新E ...
- jquery input 赋值和取值
记录一下: 在写一个input赋值,二话不说就直接利用了$('#xx').val()来进行取值和赋值,取值ok,赋值后利用alert显示正确,但是在html上并没有正确的显示出来,后来改为使用如下代码 ...
- datetimebox赋值或取值
datetimebox赋值或取值 $('#j_dateStart').datebox('setValue', ""); //赋予空值 $("#j_dateStart&qu ...
- 通过编写串口助手工具学习MFC过程——(十)UpdateData()用法和编辑框的赋值、取值
通过编写串口助手工具学习MFC过程 因为以前也做过几次MFC的编程,每次都是项目完成时,MFC基本操作清楚了,但是过好长时间不再接触MFC的项目,再次做MFC的项目时,又要从头开始熟悉.这次通过做一个 ...
- java 反射原理写了一个赋值和取值通用类
首先了解一下反射的原理,什么是反射?所谓的反射就是指java 语言在运行时拥有一项自观的能力,反射能使你得到装载到 jvm 中的类的内部信息,它不需要你在编码的时候就知道所需类的内部信息,允许程序执行 ...
- java反射获取和设置实体类的属性值 递归所有父类
最近做一个通用数据操作接口,需要动态获取和设置实体类的属性值,为了通用实体做了多重继承,开始网上找到代码都不支持父类操作,只能自己搞一个工具类了,此工具类可以设置和获取所有父类属性,代码贴下面拿走不谢 ...
随机推荐
- 统计学(检验、分布)的 python(numpy/pandas/scipy) 实现
scipy 中统计相关的 api:https://docs.scipy.org/doc/scipy/reference/stats.html https://zhuanlan.zhihu.com/p/ ...
- jquery deferred promise
<script type="text/javascript">/* Deferredstate (then,done, fail, always,pipe, progr ...
- /etc/inittab 学习
1.文件内容 2.内容讲解 http://www.2cto.com/os/201108/98426.html init的进程号是1(ps -aux | less),从这一点就能看出,init进程是系统 ...
- Zxing图片拉伸解决 Android 二维码扫描
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/aaawqqq/article/details/24852915 二维码扫描 Android Zx ...
- centos6/7安装gitlab
CentOS/RHEL 6/7安装gitlab新建 /etc/yum.repos.d/gitlab-ce.repo,内容为你的CentOS/RHEL版本:centos6 [gitlab-ce] nam ...
- JFrame 与 Frame
JFrame是Frame的子类 Frame is part of java.awt package and exists since JDK1.0. JFrame is part of javax.s ...
- HttpPostedFile类
在研究HttpRequest的时候,搞文件上传的时候,经常碰到返回HttpPostedFile对象的情况,这个对象才是真正包含文件内容的东西. 经常要获取的最重要的内容是FileName属性与Sava ...
- 1、zookeeper集群安装
前提准备3台centos7.0虚拟机 c7003:192.168.70.103 c7004:192.168.70.104 c7005:192.168.70.105 并在三台虚拟机上配置hosts为 1 ...
- HttpClient连接池
HttpClient连接池,发现对于高并发的请求,效率提升很大.虽然知道是因为建立了长连接,导致请求效率提升,但是对于内部的原理还是不太清楚.后来在网上看到了HTTP协议的发展史,里面提到了一个属性C ...
- php函数的实现
1.函数 汇编中函数对应的是一组独立的汇编指令,然后通过call指令实现函数的调用.PHP编译的opcode数组,与汇编指令对应. PHP用户自定义函数的实现就是将函数编译为独立的opcode ...