由于项目的实际需要,所以利用java反射原理写了一个简单给bean赋值和取值通用的类,在此记录下方便自己日后用到,也为需要的兄弟提供个参考例子。

工具类BeanRefUtil:

  1.  
    package com.test;
  2.  
     
  3.  
    import java.lang.reflect.Field;
  4.  
    import java.lang.reflect.Method;
  5.  
    import java.text.SimpleDateFormat;
  6.  
    import java.util.Date;
  7.  
    import java.util.HashMap;
  8.  
    import java.util.Locale;
  9.  
    import java.util.Map;
  10.  
     
  11.  
    /**
  12.  
    * java bean 反射的方法
  13.  
    */
  14.  
    public class BeanRefUtil {
  15.  
     
  16.  
    /**
  17.  
    * 取Bean的属性和值对应关系的MAP
  18.  
    * @param bean
  19.  
    * @return Map
  20.  
    */
  21.  
    public static Map<String, String> getFieldValueMap(Object bean) {
  22.  
    Class<?> cls = bean.getClass();
  23.  
    Map<String, String> valueMap = new HashMap<String, String>();
  24.  
    // 取出bean里的所有方法
  25.  
    Method[] methods = cls.getDeclaredMethods();
  26.  
    Field[] fields = cls.getDeclaredFields();
  27.  
     
  28.  
    for (Field field : fields) {
  29.  
    try {
  30.  
    String fieldType = field.getType().getSimpleName();
  31.  
    String fieldGetName = parGetName(field.getName());
  32.  
    if (!checkGetMet(methods, fieldGetName)) {
  33.  
    continue;
  34.  
    }
  35.  
    Method fieldGetMet = cls
  36.  
    .getMethod(fieldGetName, new Class[] {});
  37.  
    Object fieldVal = fieldGetMet.invoke(bean, new Object[] {});
  38.  
    String result = null;
  39.  
    if ("Date".equals(fieldType)) {
  40.  
    result = fmtDate((Date) fieldVal);
  41.  
    } else {
  42.  
    if (null != fieldVal) {
  43.  
    result = String.valueOf(fieldVal);
  44.  
    }
  45.  
    }
  46.  
    valueMap.put(field.getName(), result);
  47.  
    } catch (Exception e) {
  48.  
    continue;
  49.  
    }
  50.  
    }
  51.  
    return valueMap;
  52.  
     
  53.  
    }
  54.  
     
  55.  
    /**
  56.  
    * set属性的值到Bean
  57.  
    * @param bean
  58.  
    * @param valMap
  59.  
    */
  60.  
    public static void setFieldValue(Object bean, Map<String, String> valMap) {
  61.  
    Class<?> cls = bean.getClass();
  62.  
    // 取出bean里的所有方法
  63.  
    Method[] methods = cls.getDeclaredMethods();
  64.  
    Field[] fields = cls.getDeclaredFields();
  65.  
     
  66.  
    for (Field field : fields) {
  67.  
    try {
  68.  
     
  69.  
    String fieldSetName = parSetName(field.getName());
  70.  
    if (!checkSetMet(methods, fieldSetName)) {
  71.  
    continue;
  72.  
    }
  73.  
    Method fieldSetMet = cls.getMethod(fieldSetName, field
  74.  
    .getType());
  75.  
    String value = valMap.get(field.getName());
  76.  
    if (null != value && !"".equals(value)) {
  77.  
    String fieldType = field.getType().getSimpleName();
  78.  
    if ("String".equals(fieldType)) {
  79.  
    fieldSetMet.invoke(bean, value);
  80.  
    } else if ("Date".equals(fieldType)) {
  81.  
    Date temp = parseDate(value);
  82.  
    fieldSetMet.invoke(bean, temp);
  83.  
    } else if ("Integer".equals(fieldType)
  84.  
    || "int".equals(fieldType)) {
  85.  
    Integer intval = Integer.parseInt(value);
  86.  
    fieldSetMet.invoke(bean, intval);
  87.  
    } else if ("Long".equalsIgnoreCase(fieldType)) {
  88.  
    Long temp = Long.parseLong(value);
  89.  
    fieldSetMet.invoke(bean, temp);
  90.  
    } else if ("Double".equalsIgnoreCase(fieldType)) {
  91.  
    Double temp = Double.parseDouble(value);
  92.  
    fieldSetMet.invoke(bean, temp);
  93.  
    } else if ("Boolean".equalsIgnoreCase(fieldType)) {
  94.  
    Boolean temp = Boolean.parseBoolean(value);
  95.  
    fieldSetMet.invoke(bean, temp);
  96.  
    } else {
  97.  
    System.out.println("not supper type" + fieldType);
  98.  
    }
  99.  
    }
  100.  
    } catch (Exception e) {
  101.  
    continue;
  102.  
    }
  103.  
    }
  104.  
     
  105.  
    }
  106.  
     
  107.  
    /**
  108.  
    * 格式化string为Date
  109.  
    * @param datestr
  110.  
    * @return date
  111.  
    */
  112.  
    public static Date parseDate(String datestr) {
  113.  
    if (null == datestr || "".equals(datestr)) {
  114.  
    return null;
  115.  
    }
  116.  
    try {
  117.  
    String fmtstr = null;
  118.  
    if (datestr.indexOf(':') > 0) {
  119.  
    fmtstr = "yyyy-MM-dd HH:mm:ss";
  120.  
    } else {
  121.  
     
  122.  
    fmtstr = "yyyy-MM-dd";
  123.  
    }
  124.  
    SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK);
  125.  
    return sdf.parse(datestr);
  126.  
    } catch (Exception e) {
  127.  
    return null;
  128.  
    }
  129.  
    }
  130.  
     
  131.  
    /**
  132.  
    * 日期转化为String
  133.  
    * @param date
  134.  
    * @return date string
  135.  
    */
  136.  
    public static String fmtDate(Date date) {
  137.  
    if (null == date) {
  138.  
    return null;
  139.  
    }
  140.  
    try {
  141.  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
  142.  
    Locale.US);
  143.  
    return sdf.format(date);
  144.  
    } catch (Exception e) {
  145.  
    return null;
  146.  
    }
  147.  
    }
  148.  
     
  149.  
    /**
  150.  
    * 判断是否存在某属性的 set方法
  151.  
    * @param methods
  152.  
    * @param fieldSetMet
  153.  
    * @return boolean
  154.  
    */
  155.  
    public static boolean checkSetMet(Method[] methods, String fieldSetMet) {
  156.  
    for (Method met : methods) {
  157.  
    if (fieldSetMet.equals(met.getName())) {
  158.  
    return true;
  159.  
    }
  160.  
    }
  161.  
    return false;
  162.  
    }
  163.  
     
  164.  
    /**
  165.  
    * 判断是否存在某属性的 get方法
  166.  
    * @param methods
  167.  
    * @param fieldGetMet
  168.  
    * @return boolean
  169.  
    */
  170.  
    public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
  171.  
    for (Method met : methods) {
  172.  
    if (fieldGetMet.equals(met.getName())) {
  173.  
    return true;
  174.  
    }
  175.  
    }
  176.  
    return false;
  177.  
    }
  178.  
     
  179.  
    /**
  180.  
    * 拼接某属性的 get方法
  181.  
    * @param fieldName
  182.  
    * @return String
  183.  
    */
  184.  
    public static String parGetName(String fieldName) {
  185.  
    if (null == fieldName || "".equals(fieldName)) {
  186.  
    return null;
  187.  
    }
  188.  
    return "get" + fieldName.substring(0, 1).toUpperCase()
  189.  
    + fieldName.substring(1);
  190.  
    }
  191.  
     
  192.  
    /**
  193.  
    * 拼接在某属性的 set方法
  194.  
    * @param fieldName
  195.  
    * @return String
  196.  
    */
  197.  
    public static String parSetName(String fieldName) {
  198.  
    if (null == fieldName || "".equals(fieldName)) {
  199.  
    return null;
  200.  
    }
  201.  
    return "set" + fieldName.substring(0, 1).toUpperCase()
  202.  
    + fieldName.substring(1);
  203.  
    }
  204.  
     
  205.  
    }

Java反射 - 简单的给Bean赋值和取值的更多相关文章

  1. js实现hashtable的赋值、取值、遍历

    哈希表(Hashtable)这个概率应该是#c里面的概念,用来赋值.取值.遍历.排序操作提高效率.想起这个东西其实使我们以前经常遇到这样的面试题,一个很大的数组可能有100000个,如何快速知道它里面 ...

  2. 关于ligerform中select与text的赋值与取值

    如有下ligerform表单: var formData = [ { display: "区域", name: "QYYJ", newline: true, l ...

  3. Jquery实现数据双向绑定(赋值和取值),类似AngularJS

    <!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...

  4. 实用ExtJS教程100例-011:ExtJS Form 使用JSON数据赋值和取值

    上一节中我们演示了ExtJS Form的异步加载和提交数据,本节中我们将演示如何使用JSON数据为ExtJS Form中的字段赋值和取值. 系列ExtJS教程持续更新中,点击查看>>最新E ...

  5. jquery input 赋值和取值

    记录一下: 在写一个input赋值,二话不说就直接利用了$('#xx').val()来进行取值和赋值,取值ok,赋值后利用alert显示正确,但是在html上并没有正确的显示出来,后来改为使用如下代码 ...

  6. datetimebox赋值或取值

    datetimebox赋值或取值 $('#j_dateStart').datebox('setValue', ""); //赋予空值 $("#j_dateStart&qu ...

  7. 通过编写串口助手工具学习MFC过程——(十)UpdateData()用法和编辑框的赋值、取值

    通过编写串口助手工具学习MFC过程 因为以前也做过几次MFC的编程,每次都是项目完成时,MFC基本操作清楚了,但是过好长时间不再接触MFC的项目,再次做MFC的项目时,又要从头开始熟悉.这次通过做一个 ...

  8. java 反射原理写了一个赋值和取值通用类

    首先了解一下反射的原理,什么是反射?所谓的反射就是指java 语言在运行时拥有一项自观的能力,反射能使你得到装载到 jvm 中的类的内部信息,它不需要你在编码的时候就知道所需类的内部信息,允许程序执行 ...

  9. java反射获取和设置实体类的属性值 递归所有父类

    最近做一个通用数据操作接口,需要动态获取和设置实体类的属性值,为了通用实体做了多重继承,开始网上找到代码都不支持父类操作,只能自己搞一个工具类了,此工具类可以设置和获取所有父类属性,代码贴下面拿走不谢 ...

随机推荐

  1. 统计学(检验、分布)的 python(numpy/pandas/scipy) 实现

    scipy 中统计相关的 api:https://docs.scipy.org/doc/scipy/reference/stats.html https://zhuanlan.zhihu.com/p/ ...

  2. jquery deferred promise

    <script type="text/javascript">/* Deferredstate (then,done, fail, always,pipe, progr ...

  3. /etc/inittab 学习

    1.文件内容 2.内容讲解 http://www.2cto.com/os/201108/98426.html init的进程号是1(ps -aux | less),从这一点就能看出,init进程是系统 ...

  4. Zxing图片拉伸解决 Android 二维码扫描

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/aaawqqq/article/details/24852915  二维码扫描  Android Zx ...

  5. centos6/7安装gitlab

    CentOS/RHEL 6/7安装gitlab新建 /etc/yum.repos.d/gitlab-ce.repo,内容为你的CentOS/RHEL版本:centos6 [gitlab-ce] nam ...

  6. JFrame 与 Frame

    JFrame是Frame的子类 Frame is part of java.awt package and exists since JDK1.0. JFrame is part of javax.s ...

  7. HttpPostedFile类

    在研究HttpRequest的时候,搞文件上传的时候,经常碰到返回HttpPostedFile对象的情况,这个对象才是真正包含文件内容的东西. 经常要获取的最重要的内容是FileName属性与Sava ...

  8. 1、zookeeper集群安装

    前提准备3台centos7.0虚拟机 c7003:192.168.70.103 c7004:192.168.70.104 c7005:192.168.70.105 并在三台虚拟机上配置hosts为 1 ...

  9. HttpClient连接池

    HttpClient连接池,发现对于高并发的请求,效率提升很大.虽然知道是因为建立了长连接,导致请求效率提升,但是对于内部的原理还是不太清楚.后来在网上看到了HTTP协议的发展史,里面提到了一个属性C ...

  10. php函数的实现

    1.函数     汇编中函数对应的是一组独立的汇编指令,然后通过call指令实现函数的调用.PHP编译的opcode数组,与汇编指令对应. PHP用户自定义函数的实现就是将函数编译为独立的opcode ...