动态设置bean的属性值(类似于hibernate)

来源:互联网 发布:深圳软件产业基地 5e 编辑:程序博客网 时间:2024/06/05 03:37

不怎么喜欢用框架。感觉很耗时间。所以决定自己写一个,相似的功能。每回在设置bean的属性时总是很麻烦。

所以像让程序动态的去获取bean的属性值。在方法中只要扔一个空的bean和sql进去,就可以返回一个生成好的bean方法。这样使用起来就很方便了。

下面是我的初步的一个探索,很大家分享一下

首先是一个Bean文件


package com.test.string;public class Bean {private int id;private String name;private String pwd;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}
这个没什么。然后是主体类

包含两个方法

package com.test.string;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.util.HashMap;import java.util.Map;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test {public Bean setBeanFromDB() {try {//这里模拟了数据库查询的内容Map<String, Object> userMap = new HashMap<String, Object>();userMap.put("id", 1001);userMap.put("name", "isoftstone");userMap.put("pwd", "234234");//这里模拟结束Bean bean = new Bean();BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());PropertyDescriptor[] propertyDesc = beanInfo.getPropertyDescriptors();for (int i = 0; i < propertyDesc.length; i++) {if (propertyDesc[i].getName().compareToIgnoreCase("class") == 0)continue;String column = propertyDesc[i].getName();System.out.print(propertyDesc[i].getName()+":");Object strValue = userMap.get(column);System.out.println(strValue);if (strValue != null) {Object[] oParam = new Object[] {};Method mr = propertyDesc[i].getWriteMethod();if (mr != null) {oParam = new Object[] { (strValue) };try {// 注意这里的参数。mr.invoke(bean, oParam);} catch (IllegalArgumentException iea) {System.out.println("参数错误。");iea.printStackTrace();}}}}return bean;} catch (Exception e) {e.printStackTrace();}return null;}public void readBean(Bean bean) {Method metd = null;String fdname = null;try {Field[] fds = bean.getClass().getDeclaredFields();// 获取他的字段数组for (Field field : fds) {// 遍历该数组fdname = field.getName();// 得到字段名,metd = bean.getClass().getMethod("get" + change(fdname), null);// 根据字段名找到对应的get方法,null表示无参数System.out.println(fdname + ":" + metd.invoke(bean, null));}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static String change(String src) {if (src != null) {StringBuffer sb = new StringBuffer(src);sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));return sb.toString();} else {return null;}}public static void main(String[] args) {Test test = new Test();Bean bean = new Bean();bean.setId(100);bean.setName("hello");bean.setPwd("hello");test.readBean(bean);System.out.println("from DB-----------");bean = test.setBeanFromDB();}}


关键的地方都加了注释,大家可以跑跑看。




原创粉丝点击