首先我们先写好我们的对象Person
package com.xiva.bean;
public class Person {
private Long personId;
private String name;
private String password;
private String email;
public Person(){
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString(){
return this.personId + this.name + this.email + this.password;
}
}
有时我们从数据库中查找到一个object数组,这是我们需要一个一个将值写入到我们的对象,并保存为一个list。也许10个左右的属性你还可以接受,但是当属性达到30以上时,而且你的属性还在不断的变化。这是你的工作量可能就会大大的增加了。这是我写这个方法的背景。
下面看看我的处理方式:
package com.xiva.bean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
*
* @author XIVA
*
*/
public class TempRef {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// TODO Auto-generated method stub
Person p = new Person();
Class<Person> clazz = Person.class;
//获取所有属性
Field[] field = clazz.getDeclaredFields();
//各属性所对应的值
Object[] values = {"2","xiva",null,"xgt@126.com"};
for(int i = 0;i < field.length; i++){
System.out.println(field[i].getName() + field[i].getType());
String methodName = "set" + fir2Upper(field[i].getName());
//根据方法名获取method对象
Method setMethod = clazz.getMethod(methodName, new Class[]{ field[i].getType()});
//执行方法,并根据各属性的类型不一样赋予相应类型的值
if(field[i].getType().equals(Long.class))
setMethod.invoke(p, new Object[]{values[i]==null?new Long(0):Long.parseLong(values[i].toString())});
else if(field[i].getType().equals(String.class)){
setMethod.invoke(p, new Object[]{values[i]==null?"":values[i].toString()});
}
}
System.out.println(p);
}
/**
* 首字母大写
* @param property
* @return
*/
public static String fir2Upper(String property){
String firChar = property.substring(0, 1);
String upperChar = firChar.toUpperCase();
String res = upperChar + property.substring(1);
return res;
}
}
其中有一个限制是我们必须得注意到的,就是我们的属性顺序和我们的值顺序是一一对应的,也就是说赋值时,你Person类属性声明的顺序,就是你values数组中值的顺序。
其实获取meta,是可以直接使用rowMap来实现的,但是此处我们用这种方式。