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反射获取和设置实体类的属性值 递归所有父类
最近做一个通用数据操作接口,需要动态获取和设置实体类的属性值,为了通用实体做了多重继承,开始网上找到代码都不支持父类操作,只能自己搞一个工具类了,此工具类可以设置和获取所有父类属性,代码贴下面拿走不谢 ...
随机推荐
- linux-*.filetype.bz2 unzip
how to unzip *.bz2 file? wget http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 unzip ...
- show point on image
show point on image... for ( int i = 0; i < probp.size(); i++ ) { cv::Point pt = probp[i]; Distan ...
- visual studio 2014 新特性
原文如下: Visual Studio "14" CTP Today, we are making available a first community technology p ...
- No result defined for action com.nynt.action.ManageAction and result input问题
No result defined for action com.nynt.action.ManageAction and result input 问题原因: 1). 在action类中定义的一个r ...
- C语言面试题3
编程题 1.读文件file1.txt的内容(例如): 123456 输出到file2.txt: 563412 #include <stdio.h> #include <stdlib. ...
- POJ2777(线段树裸题)
题目:http://poj.org/problem?id=2777 别忘了各地的return: 有可能输入的L<R,手动swap: 似乎是多组输入? pushup和pushdown的位置. (原 ...
- Angular 4 表单校验1
1.html <form [formGroup]="formModel" (submit)="submit()"> <div> 用户名: ...
- 深入理解ASP.NET MVC(1)
系列目录 ASP.NET MVC请求的服务过程 下图是书中的截图,表述了一次通常的ASP.NET MVC请求的服务过程: 从图中可以初步看出一个HttpRequest是如何被ASP.NET和ASP.N ...
- 最新hadoop入门教程汇总篇(附详细图文步骤)
关于hadoop的分享此前一直都是零零散散的想到什么就写什么,整体写的比较乱吧.最近可能还算好的吧,毕竟花了两周的时间详细的写完的了hadoop从规划到环境安装配置等全部内容.写过程不是很难,最烦的可 ...
- 联想服务器配置 RAID
联想服务器配置 RAID BIOS 中配置 RAID 阵列卡 x3650 和 x3850 一.进入 RAID 1.在开机自检时按 F1 进入 UEFI 配置界面 2.选择 System Setting ...