日期:2014-05-20 浏览次数:20921 次
public class CarForm { public String brand; public String type; public int price; public int count; }
public class CarDto { public String brand; public String type; public int price; public int count; public String encribe; }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * 模拟提交表单 * @author ... * */ public class CarService { public CarForm submitForm(Object form, String values) { //以&分隔开来 String[] keyValues = values.split("&"); Map<String, Object> valueMap = new HashMap<String, Object>(); for (String s : keyValues) { valueMap.put(s.substring(0, s.indexOf("=")), s.substring(s.indexOf("=") + 1)); } Field[] fds = form.getClass().getDeclaredFields(); String typeClass; Object value; for (Field fd : fds) { try { typeClass = fd.getType().getSimpleName(); value = valueMap.get(fd.getName()); //需要判断属性类型, if (typeClass.equals("int")) { value = Integer.parseInt(value.toString()); } if (typeClass.equals("String")) { value = value.toString(); } fd.set(form, value); } catch (Exception e) { e.printStackTrace(); } } return (CarForm) form; } }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * 两个对象同名属性复制值 * @author chenglixiang * */ public class Copys { public static void copy(CarForm src, CarDto dest) { Map<String, Object> srcMap = new HashMap<String, Object>(); Field[] srcFields = src.getClass().getDeclaredFields(); for (Field fd : srcFields) { try { srcMap.put(fd.getName(), fd.get(src)); //获取属性值 } catch (Exception e) { e.printStackTrace(); } } Field[] destFields = dest.getClass().getDeclaredFields(); for (Field fd : destFields) { if (srcMap.get(fd.getName()) == null) { continue; } try { fd.set(dest, srcMap.get(fd.getName())); //给属性赋值 } catch (Exception e) { e.printStackTrace(); } } } }
import java.lang.reflect.Field; public class Test { public static void main(String[] args) { //模拟提交表单的字符串 String values = "brand=奥迪&type=A6&price=60&count=1000"; CarService carService = new CarService(); CarForm carForm = new CarForm(); carForm = carService.submitForm(carForm, values); CarDto carDto = new CarDto(); Copys.copy(carForm, carDto); carDto.encribe = "详细说明详细说明"; Field[] fds = carDto.getClass().getDeclaredFields(); for (Field fd : fds) { try { System.out.println(fd.getName() + "=" + fd.get(carDto)); } catch (Exception e) { e.printStackTrace(); } } } }