Grails框架中有个很好玩(偷懒)的功能, 实例化对象时可以将map类型的数据作为参数, 如果类中有成员变量名称刚好能在map中找到, 那么map中这个key的值可赋给它.
这种功能术语叫"数据绑定"(DataBinding), 很多框架都有它, grails做得最极致.
所以我就弄了一个差不多功能的, 供大家参考. 废不多说, 直上代码:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.HashMap;
@SuppressWarnings("unchecked")
public class Aree {
public Aree(){}
private String abs;
private Integer bli;
private String cli;
public void setAbs(String abs){this.abs = abs;}
public String getAbs(){return this.abs;}
public void setBli(Integer bli){this.bli = bli;}
public Integer getBli(){return this.bli;}
public void setCli(String cli){this.cli = cli;}
public String getCli(){return this.cli;}
@SuppressWarnings("rawtypes")
public Aree(Map<String,Object> map){
super();
System.out.println("\n=====↓↓开始new对象↓↓===========================");
Class thisClass = this.getClass();
Field[] fields = thisClass.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
System.out.println("fieldName: "+fieldName);
if(!map.containsKey(fieldName)){
System.out.println("continue\n");
continue;
}
Method method = null;
Object val = map.get(fieldName);
System.out.println(String.format("map.get(%s): %s", fieldName, val+""));
String upper = fieldName.substring(0, 1).toUpperCase();//将第一个字母转换为大写
String setter = "set" + upper + fieldName.substring(1);//合成set方法
System.out.println("setter: "+setter);
Class v_class = val.getClass();//指定调用方法的类型
try {
method = thisClass.getMethod(setter, v_class);//通过方法名获取 thisClass 的方法,参数类型为 v_class 的类型
System.out.println(method==null?"没有":""+"找到方法");
method.invoke(this, val);//通过 thisClass 的实例调用setter方法,val 为参数值
}
catch (Exception e) {
System.out.println("error");
}
System.out.println("---------------------循环------------------------");
}
System.out.println("=======↑↑对象new玩乐↑↑===========================");
}
public static void main(String[] args){
Map map = new HashMap<String, Object>();
map.put("abs", "aaa");
map.put("bli", 2);
//map.put("cli", "ccc");
Aree a = new Aree(map);
System.out.println("\n\n============main print===============================");
System.out.println("abs: "+a.getAbs());
System.out.println("bli: "+a.getBli());
System.out.println("cli: "+a.getCli());
}
}
都看到了吧, 其实就是反射, 反射就玩乐…