反射机制实现javaBeans自动赋值
开发中常常遇到两个beans相同字段之间值传递中大量的x.setXXXX(y.getXXX())语句;
字段多了比较繁琐,所以在这里就利用反射机制实现自动赋值。
考虑反射机制的效率问题,字段不多就手动设置更好。
/** * javaBeans自动将相同字段值赋给给另外一个javaBeans * @param src * @param target * @throws Exception */public static void CopyBeans2Beans(Object src, Object target) throws Exception {Field[] srcFields = src.getClass().getDeclaredFields();Method[] methods = target.getClass().getMethods();for (Field field : srcFields) {//不检查访问修饰符,如果有私有变量请一定要设置field.setAccessible(true);String methodName = "set"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);for (Method method : methods) {if(methodName.equals(method.getName()))method.invoke(target, field.get(src));}}}public static void CopyBeans2Beans(Object from, Object to) {try {BeanInfo toBI = Introspector.getBeanInfo(to.getClass());PropertyDescriptor[] toPD = toBI.getPropertyDescriptors();BeanInfo fromBI = Introspector.getBeanInfo(from.getClass());PropertyDescriptor[] fromPD = fromBI.getPropertyDescriptors();HashMap<String, PropertyDescriptor> fromMap = new HashMap<String, PropertyDescriptor>();for (PropertyDescriptor pd : fromPD)fromMap.put(pd.getName(), pd);for (PropertyDescriptor toP : toPD) {Method setMethod = toP.getWriteMethod();PropertyDescriptor formP = fromMap.get(toP.getName());if (formP == null)// 如果from没有此属性的get方法,跳过continue;Method getMethod = fromMap.get(toP.getName()).getReadMethod();if (getMethod != null && setMethod != null) {Object result = getMethod.invoke(from);if(result==null)continue;if(result.getClass()!= java.lang.String.class)continue;setMethod.invoke(to, result);}}} catch (Exception e) {e.printStackTrace();}} 1 楼 redish 2009-08-10 common包有个BeanUtil工具,很不错! 2 楼 sikeh 2009-10-25 Apache Commons BeanUtils...