先上代码
public class ReflectUtil {
@SuppressWarnings("rawtypes")
public static Object setValue(Class classType,String[] fields,String[] values,String formart){
Map<String, Integer> fieldsMap = new HashMap<String, Integer>();
for (int i = 0; i < fields.length; i++) {
fieldsMap.put(fields[i],i);
}
Object bean = null;
try {
bean = classType.newInstance();
Field[] fs = classType.getDeclaredFields();
for(int i = 0 ; i < fs.length; i++){
Field f = fs[i];
f.setAccessible(true); //设置些属性是可以访问的
String fieldName = f.getName();
if(fieldsMap.get(fieldName)!=null){
Integer index = fieldsMap.get(fieldName);
String type = f.getType().getName();//得到此属性的类型
setValueByType(type, index, values, bean, f, formart);
}
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return bean;
}
/**
* 具体操作类属性的值
* @param type
* @param index
* @param values
* @param bean
* @param f
* @param formart
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private static void setValueByType(String type,int index,String[] values,Object bean,Field f,String formart) throws IllegalArgumentException, IllegalAccessException{
if (type.endsWith("String")) {
f.set(bean,values[index]) ; //给属性设值
}else if(type.equalsIgnoreCase("Date")||type.equalsIgnoreCase("java.util.Date")){
f.set(bean,DateUtil.parseDate(values[index], formart)) ; //给属性设值
}
}
public static void main(String[] args) {
// String[] fields = {"username","password","nickname","lastLoginTime"};
// String[] values = {"刘德华","12313","天王","2012-2"};
//
// Account info = (Account) setValue(Account.class, fields, values, "yyyy-MM");
//
// System.out.println(info.getUsername()+" - " + info.getPassword()+" - " + info.getNickname()+" - " + info.getLastLoginTime());
}
}
其中 fields 和 values要一一对应上,不能错开或者缺少
那这个在哪个会用到呢,之前在做excel导入的时候,需要把excel中的数据转化为对象集合,那么这个工具类可以很方便帮你完成封装转化