通过调用静态方法populate可以用map给bean赋值,简单创建个模型,模拟一下实现. 用的都是最简单的模型.
创建3个类
UserBean: 模拟Object bean
MyPopulate: 模拟populate实现方法
Test:主程序
1.UserBean
package com.itcast.test;
public class UserBean {
private String name; //姓名
private String age; //年龄
private String gender; //性别
private String addr; //地址
@Override
public String toString() {
return "UserBean [name=" + name + ", age=" + age + ", gender=" + gender + ", addr=" + addr + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
2.MyPopulate
package com.itcast.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class MyPopulate {
UserBean bean = new UserBean();
Map<String, String> map = new HashMap<String, String>();
void myPopulate(UserBean bean, Map<String, String> map) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class beanClass = bean.getClass();
//通过反射获取bean里面的方法
Method md[] = beanClass.getMethods();
//遍历bean里面所有的方法
for (Method method : md) {
String name = method.getName();
//遍历map里面的所有键值对
for(Map.Entry<String, String> entry: map.entrySet()){
//判断map键与方法名相关的,如果有,将map中的值传入方法,相当于给bean里的属性赋值
if(("set"+entry.getKey()).equalsIgnoreCase(name)){
System.out.println("***"+name+"***");
Method md02 = beanClass.getMethod(name, String.class);
//执行setXXX方法
md02.invoke(bean, entry.getValue());
}
//System.out.println(entry.getKey() + " " + entry.getValue());
}
//System.out.println(name);
}
}
}
3.Test
package com.itcast.test;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
MyPopulate mpop = new MyPopulate();
UserBean bean = new UserBean();
Map<String, String> map = new HashMap<String, String>();
map.put("name", "zhangsan");
map.put("age", "18");
map.put("gender", "male");
map.put("addr", "beijing");
mpop.myPopulate(bean, map);
System.out.println(bean.toString());
}
}
输出结果:
***setAge***
***setGender***
***setAddr***
***setName***
UserBean [name=zhangsan, age=18, gender=male, addr=beijing]
通过反射获取bean对象里的所有方法,将方法名与map键名进行比对,有相关的就通过反射调用此方法名的方法,实现setXXX给bean对象属性赋值.