/** * map to bean * 转换过程中,由于属性的类型不同,需要分别转换。 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器 * * @param map 待转换的 map * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同 * @throws IllegalAccessException * @throws InvocationTargetException */ private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException { //注册几个转换器 ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class); ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class); //注册一个类型转换器 解决 common-beanutils 为 Date 类型赋值问题 ConvertUtils.register(new Converter() { // @Override public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。 value :目前参数的值。 // System.out.println(String.format("value = %s", value)); if (value == null || value.equals("") || value.equals("null")) return null; Date date = null; try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = dateFormat.parse((String) value); } catch (Exception e) { e.printStackTrace(); } return date; } }, Date.class); BeanUtils.populate(bean, map); }
public static void check() { if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) { loadDefaultConverters(); for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) { try { final StringCodec<?> codecInstance = entry.getValue().newInstance(); ConvertUtils.register(new Converter() { @Override public Object convert(Class type, Object value) { return value == null ? null : codecInstance.fromString(value.toString()); } }, entry.getKey()); } catch (Exception ex) { throw new RuntimeException(ex); } } } }
public String[] convertToString(Object[] objects) { String[] strings = new String[objects.length]; int i = 0; for (Object object : objects) { if (object != null) { Converter converter = ConvertUtils.lookup(object.getClass()); if (converter != null) { strings[i++] = converter.convert(object.getClass(), object).toString(); } else { strings[i++] = object.toString(); } } else { strings[i++] = ""; } } return strings; }
/** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set */ public void set(String name, Object value) { // Set the page number (for validator) if ("page".equals(name)) { if (value == null) { page = 0; } else if (value instanceof Integer) { page = ((Integer)value).intValue(); } else { try { page = ((Integer)ConvertUtils.convert(value.toString(), Integer.class)).intValue(); } catch (Exception ignore) { page = 0; } } } dynaBean.set(name, value); }
/** * 基于Apache BeanUtils转换字符串到相应类型. * * @param value 待转换的字符串. * @param toType 转换目标类型. */ public static Object convertToObject(String value, Class<?> toType) { Object cvt_value=null; try { cvt_value=ConvertUtils.convert(value, toType); // if(toType==Date.class){ // System.out.println("0----0"); // SimpleDateFormat dateFormat=null; // try{ // dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // cvt_value=dateFormat.parse(value); // }catch(Exception e){ // dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // cvt_value=dateFormat.parse(value); // } // } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return cvt_value; }
private static void entity2Dto() { EUser u = new EUser(); u.setId(1l); u.setUsername("yoking"); u.setCreationDate(new Date(System.currentTimeMillis())); UserDTO user = new UserDTO(); ConvertUtils.register(new DateStringConverter(), String.class); try { BeanUtils.copyProperties(user, u); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } System.out.println(user); }
private static void dto2Entity() { UserDTO user = new UserDTO(); user.setId(1l); user.setUsername("joking"); user.setCreationDate("2016-04-20"); EUser u = new EUser(); ConvertUtils.register(new DateStringConverter(), Date.class); try { BeanUtils.copyProperties(u, user); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } System.out.println(u); }
private static Object toValue(String initial, Class clazz) { Object value; try { if (initial != null) { value = ConvertUtils.convert(initial, clazz); } else { if (clazz.isArray()) { value = Array.newInstance(clazz.getComponentType(), 0); } else { value = clazz.newInstance(); } } } catch (Throwable t) { log.warn("No es pot convertir '" + initial + "' a " + clazz.getName()); value = null; } return (value); }
@Override public <T> List<T> getList(Object aKey, Class<T> aElementType) { List list = get(aKey, List.class); if(list == null) { return null; } List<T> typedList = new ArrayList<>(); for(Object item : list) { if(aElementType.equals(Accessor.class) || aElementType.equals(MapObject.class)) { typedList.add((T)new MapObject((Map<String, Object>) item)); } else { typedList.add((T)ConvertUtils.convert(item,aElementType)); } } return Collections.unmodifiableList(typedList); }
@JsonIgnore public Map<String, Object> getVariableMap() { ConvertUtils.register(new DateConverter(), java.util.Date.class); if (StringUtils.isBlank(keys)) { return map; } String[] arrayKey = keys.split(","); String[] arrayValue = values.split(","); String[] arrayType = types.split(","); for (int i = 0; i < arrayKey.length; i++) { String key = arrayKey[i]; String value = arrayValue[i]; String type = arrayType[i]; Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue(); Object objectValue = ConvertUtils.convert(value, targetType); map.put(key, objectValue); } return map; }
/** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set */ public void set(String name, Object value) { // Set the page number (for validator) if ("page".equals(name)) { if (value == null) { page = 0; } else if (value instanceof Integer) { page = ((Integer) value).intValue(); } else { try { page = ((Integer) ConvertUtils.convert(value.toString(), Integer.class)).intValue(); } catch (Exception ignore) { page = 0; } } } dynaBean.set(name, value); }
/** * 将Map的值装入指定的对象中 * * @param obj 对象 * @param properties map值 * @throws java.lang.reflect.InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ public static void fastPopulate(Object obj, Map<String, Object> properties) { Class<?> classz = obj.getClass(); Map<String, PropertiesEntry> map = getFastBeanCache().getPropertiesEntryMap(classz); if (map.size() > 0) { try { for (Map.Entry<String, Object> entry : properties.entrySet()) { PropertiesEntry pe = map.get(entry.getKey()); if (pe != null) { if (pe.getSet() != null) { if (entry.getValue() != null) { Object v = ConvertUtils.convert(entry.getValue(), pe.getType()); pe.getSet().invoke(obj, v); } else { entry.setValue(null); } } } } } catch (Exception e) { throw new RuntimeException(e); } } }
@Test public void test4() throws Exception{ String name="aaa"; String password="123"; String age="24"; String birthday="1980-09-09"; //ʹ��apache���Ѿ�ʵ��Convert�ӿڵ�ת������DateLocaleConverterʵ�ֽ�ǰ�˷��͵��������͵��ַ�������ת��Ϊbean�������Ե������������� ConvertUtils.register(new DateLocaleConverter(), Date.class); Person bean=new Person(); BeanUtils.setProperty(bean, "name", name);//��ʾ�����ĸ�bean���ĸ����ԣ���Ϊ������Ը�ֵΪvalue BeanUtils.setProperty(bean, "password", password); BeanUtils.setProperty(bean, "age", age);//ֻ֧���ַ�����8�ֻ������������Զ�ת�� BeanUtils.setProperty(bean, "birthday", birthday); System.out.println(bean.getName());//aaa System.out.println(bean.getPassword());//123 System.out.println(bean.getAge());//24�����Կ���ǰ̨���ݹ������ݶ������ַ������͵ģ�����bean����age������int�ͣ�Ҳ����beanUtils���֧�ֽ�ǰ̨���ַ��������Զ�ת��Ϊ���ֻ����������ݣ����Ǹ������ͣ��Ͳ������ˣ���Ҫ����Ϊ��������ע��һ��ת��������beanUtils�����ת����ȥ��ǰ̨string����ת��Ϊbean����ĸ����������ԣ����������� System.out.println(bean.getBirthday().toLocaleString());//1980-9-9 0:00:00 }
@Test public void test5() throws Exception{ Map map=new HashMap(); map.put("name", "aaa"); map.put("password", "123"); map.put("age", "23"); map.put("birthday", "1980-09-09"); //ʹ��apache���Ѿ�ʵ��Convert�ӿڵ�ת������DateLocaleConverterʵ�ֽ�ǰ�˷��͵��������͵��ַ�������ת��Ϊbean�������Ե������������� ConvertUtils.register(new DateLocaleConverter(), Date.class); Person bean =new Person(); BeanUtils.populate(bean, map);//ʹ��map���ϵ�key-valueֵ���bean��������ԣ��ڲ��ǽ�map�ؼ���keyΪname������valueֵ��䵽bean�����Ӧ��name����ֵ�ϣ���map�Ĺؼ������Ʊ�����bean���Ե�����������һ�� System.out.println(bean.getName());//aaa System.out.println(bean.getPassword());//123 System.out.println(bean.getAge());//24�����Կ���ǰ̨���ݹ������ݶ������ַ������͵ģ�����bean����age������int�ͣ�Ҳ����beanUtils���֧�ֽ�ǰ̨���ַ��������Զ�ת��Ϊ���ֻ����������ݣ����Ǹ������ͣ��Ͳ������ˣ���Ҫ����Ϊ��������ע��һ��ת��������beanUtils�����ת����ȥ��ǰ̨string����ת��Ϊbean����ĸ����������ԣ����������� System.out.println(bean.getBirthday().toLocaleString());//1980-9-9 0:00:00 }
public static Object Map2Bean(Class type, Map map) throws Exception { ConvertUtils.register(new DateConvert(), Date.class); BeanInfo beanInfo = Introspector.getBeanInfo(type); Object obj = type.newInstance(); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { String propertyName = descriptor.getName(); if (!(map.containsKey(propertyName.toUpperCase()))) continue; try { Object value = map.get(propertyName.toUpperCase()); BeanUtils.setProperty(obj, propertyName, value); } catch (Exception e) { e.printStackTrace(); } } return obj; }
@SuppressWarnings("unchecked") public <X> List<X> findListByHaloView(HaloMap parameter) { Integer begin = 0; Integer end = null; if (null != parameter.get(HaloDao.ADDBEGIN)) { begin = (Integer) ConvertUtils.convert(parameter.get(HaloDao.ADDBEGIN), Integer.class); parameter.remove(HaloDao.ADDBEGIN); } if (null != parameter.get(HaloDao.ADDEND)) { end = (Integer) ConvertUtils.convert(parameter.get(HaloDao.ADDEND), Integer.class); parameter.remove(HaloDao.ADDEND); } SQLQuery query = null; if (this.entityType.getName().equals("com.ht.halo.map.HaloViewMap")) { query = CreateMySqlQueryByHaloViewToMap(parameter); } else { query = CreateMySqlQueryByHaloViewToBean(parameter); } if (null != end) { query.setFirstResult(begin); query.setMaxResults(end - begin); } return query.list(); }
/** * Helper method to {@code expandSearchTerms}: builds up a query string with * joining ampersands and converts the value given into a string. * * @param query The StringBuilder which is building up the query. * @param argument The search parameter. * @param value The value to search for. * * @throws IllegalSearchTermException if {@code value} is null. * * @see #expandSearchTerms(Map) * @see ConvertUtilsBean#convert(Object) */ private void appendQueryTerm(StringBuilder query, String argument, Object value) { if (value == null) { // This message is sensible as find() will not call this method if it // finds the term's immediate value is null. It will only get here with // value == null when looping through an array or collection. throw new IllegalSearchTermException( argument, "Search term \"" + argument + "\" contains a null value."); } String strValue = ConvertUtils.convert(value); if (query.length() > 0) { query.append('&'); } query.append(argument); query.append('='); query.append(strValue); }
public void setEnvironmentVariable(String key, Object value, boolean check) { if (check) { if (!environment.containsKey(key)) { throw new IllegalArgumentException("Invalid key - " + key); } Object old = environment.get(key); if (!old.getClass().equals(value.getClass())) { value = ConvertUtils.convert(value, old.getClass()); if (!old.getClass().equals(value.getClass())) { throw new IllegalArgumentException("Invalid value type - " + value.getClass().getName() + " should be " + old.getClass().getName()); } } } Object prev = environment.get(key); if ((value != null && !value.equals(prev)) || (value == null && prev != null)) { setChanged(); } notifyObservers(new UpdateEnvironmentEvent(key, prev, value)); environment.put(key, value); }
@XmlTransient @JsonIgnore public Map<String, String> getAsMap() { Map<String, String> entityMap = Maps.newTreeMap(); try { for (PropertyDescriptor prop : propertyCache.get(this.getClass())) { String property = prop.getName(); String className = prop.getPropertyType().getName(); if (className.startsWith("java.util.") && !className.equals("java.util.Date") || className.startsWith("net.techreadiness") || "class".equals(property) || "asMap".equals(property) || "columnsAsMap".equals(property) || "columnFieldInfo".equals(property) || "extendedDefinition".equals(property) || "exts".equals(property) || "serviceObjectType".equals(property) || "extAttributes".equals(property)) { // TODO : I think we have to ignore this for now continue; } Object obj = prop.getReadMethod().invoke(this); entityMap.put(property, ConvertUtils.convert(obj)); } return entityMap; } catch (Exception e) { throw new RuntimeException(e); } }
/** * @see Comparator#compare(Object, Object) */ @Override public int compare(Object obj1, Object obj2) { double dbl1 = 0; if (obj1 instanceof Number) { dbl1 = ((Number) obj1).doubleValue(); } else if (obj1 != null) { dbl1 = ((Number) ConvertUtils.convert(obj1.toString(), Number.class)).doubleValue(); } double dbl2 = 0; if (obj2 instanceof Number) { dbl2 = ((Number) obj2).doubleValue(); } else if (obj1 != null) { dbl2 = ((Number) ConvertUtils.convert(obj2.toString(), Number.class)).doubleValue(); } return new Double(dbl1).compareTo(new Double(dbl2)); }
public static void registerConverters() { ConvertUtils.register(new StringConverter(), String.class); //date ConvertUtils.register(new DateConverter(null),java.util.Date.class); ConvertUtils.register(new SqlDateConverter(null),java.sql.Date.class); ConvertUtils.register(new SqlTimeConverter(null),Time.class); ConvertUtils.register(new SqlTimestampConverter(null),Timestamp.class); //number ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ShortConverter(null), Short.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); }
public static Object convertGenericType(String fieldName, Object value, FieldType type) { if (FieldType.DATE == type) { return convertDate(fieldName, value); } if (type.getClasses().length == 0) return error(INVALID_FORMAT, fieldName); Class<?> clz = type.getClasses()[0]; value = ConvertUtils.convert(value, clz); if (value == null || !clz.isAssignableFrom(value.getClass())) { return error(INVALID_FORMAT, fieldName); } return value; }
@SuppressWarnings("unchecked") public static <T> List<T> getFieldList(Map<String,Object> data, String name, Class<T> type) { Map<String,Object> fields = CollectionUtils.castMap(data.get(FIELDS)); Object value = fields.get(name); if ( value == null ) { return null; } if ( value instanceof List ) { List<?> list = (List<?>)value; Object firstValue = list.size() > 0 ? list.get(0) : null; if ( list.size() > 0 && firstValue != null && type.isAssignableFrom(firstValue.getClass()) ) { return (List<T>) list; } List<T> result = new ArrayList<T>(list.size()); for ( Object obj : list ) { result.add((T)ConvertUtils.convert(obj, type)); } return result; } else { throw new IllegalArgumentException("[" + value + "] is not a list"); } }
public Map<String, Object> getVariableMap() { Map<String, Object> vars = new HashMap<String, Object>(); ConvertUtils.register(new DateConverter(), java.util.Date.class); if (StringUtil.isBlank(keys)) { return vars; } String[] arrayKey = keys.split(","); String[] arrayValue = values.split(","); String[] arrayType = types.split(","); for (int i = 0; i < arrayKey.length; i++) { String key = arrayKey[i]; String value = arrayValue[i]; String type = arrayType[i]; Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue(); Object objectValue = ConvertUtils.convert(value, targetType); vars.put(key, objectValue); } return vars; }
@SuppressWarnings("unchecked") public static <T> List<T> getFieldList(Map<String,Object> data, String name, Class<T> type) { Map<String,Object> fields = CollectionUtils.castMap(data.get(FIELDS)); Object value = fields.get(name); if ( value == null ) { return null; } if ( value instanceof List ) { List<?> list = (List<?>)value; if ( list.size() > 0 && type.isAssignableFrom(list.get(0).getClass()) ) { return (List<T>) list; } List<T> result = new ArrayList<T>(list.size()); for ( Object obj : list ) { result.add((T)ConvertUtils.convert(obj, type)); } return result; } else { throw new IllegalArgumentException("[" + value + "] is not a list"); } }
/** * @param parameters * @param request * @param values * @return */ private static Object[] getActionParameterValues(List<ParameterMetaData> parameters, Map<String, Object> body, Map<String, Object> values) { if (body != null) { values.putAll(body); } Object[] params = new Object[parameters.size()]; for (int i = 0; i < parameters.size(); i++) { ParameterMetaData param = parameters.get(i); Object value = values.get(param.getName()); if (value != null && ! value.getClass().equals(param.getType())) { value = ConvertUtils.convert(value, param.getType()); } params[i] = value; } return params; }
private void setProperty(final MetaDataProvider instance, final String propertyName, final String propertyValue) throws MojoExecutionException { final Class<? extends MetaDataProvider> metaDataProviderClass = instance.getClass(); try { final Field field = findField(metaDataProviderClass, propertyName); field.setAccessible(true); final Class<?> type = field.getType(); final Object typedPropertyValue = ConvertUtils.convert(propertyValue, type); field.set(instance, typedPropertyValue); } catch (final Exception e) { throw new MojoExecutionException( "Cannot set property '" + propertyName + "' to value '" + propertyValue + "' for the instance of class '" + metaDataProviderClass.getName() + "'.", e); } }
protected void addHiddenSlot(String slot, Object value, String converterName) throws JspException { if (slot == null) { slot = getContainerParent().getSlot(); } if (slot == null) { throw new RuntimeException("slot must be defined or directly or in the parent edit tag"); } Class<Converter> converter = null; if (converterName != null) { try { converter = (Class<Converter>) Class.forName(converterName); } catch (ClassNotFoundException e) { throw new JspException("the specified converter could not be found: " + converterName); } } boolean multiple = isMultiple(); getContainerParent().addHiddenSlot(slot, multiple, ConvertUtils.convert(value), converter); }
@Override public Object getConvertedValue(MetaSlot slot) { if (hasConverter()) { return getConverter().convert(slot.getStaticType(), getValues()); } if (slot.hasConverter()) { try { return slot.getConverter().newInstance().convert(slot.getStaticType(), getValues()); } catch (Exception e) { throw new RuntimeException("converter specified in meta slot generated an exception", e); } } return ConvertUtils.convert(getValues(), slot.getStaticType()); }
@Override public Object getConvertedValue(MetaSlot slot) { if (hasConverter()) { return getConverter().convert(slot.getStaticType(), getValue()); } if (slot.hasConverter()) { try { return slot.getConverter().newInstance().convert(slot.getStaticType(), getValue()); } catch (Exception e) { throw new RuntimeException("converter specified in meta slot generated an exception: " + e, e); } } if (getValue() == null) { return null; } return ConvertUtils.convert(getValue(), slot.getStaticType()); }
protected void register() { super.register(); ConvertUtils.register(new MyBooleanConverter(), Boolean.TYPE); ConvertUtils.register(new NullSafeConverter(new MyBooleanConverter()), Boolean.class); ConvertUtils.register(new NullSafeConverter(new ByteArrayConverter()), byte[].class); ConvertUtils.register(new PercentWrapper(new DoubleConverter()), Double.TYPE); ConvertUtils.register(new NullSafeConverter(new PercentWrapper(new DoubleConverter())), Double.class); ConvertUtils.register(new PercentWrapper(new FloatConverter()), Float.TYPE); ConvertUtils.register(new NullSafeConverter(new PercentWrapper(new FloatConverter())), Float.class); ConvertUtils.register(new ChargeWrapper(new IntegerConverter()), Integer.TYPE); ConvertUtils.register(new NullSafeConverter(new ChargeWrapper(new IntegerConverter())), Integer.class); ConvertUtils.register(new NullSafeConverter(new DateFriendlyStringConverter()), String.class); ConvertUtils.register(new LenientTimestampConverter(), java.sql.Timestamp.class); ConvertUtils.register(new LenientDateConverter(), java.util.Date.class); }
/** * Convert the specified locale-sensitive input object into an output object of the * specified type. * * @param <T> The desired target type of the conversion * @param type Data is type to which this value should be converted * @param value is the input object to be converted * @param pattern is the pattern is used for the conversion; if null is * passed then the default pattern associated with the converter object * will be used. * @return The converted value * * @throws ConversionException if conversion cannot be performed * successfully */ public <T> T convert(final Class<T> type, final Object value, final String pattern) { final Class<T> targetType = ConvertUtils.primitiveToWrapper(type); if (value == null) { if (useDefault) { return getDefaultAs(targetType); } else { // symmetric beanutils function allows null // so do not: throw new ConversionException("No value specified"); log.debug("Null value specified for conversion, returing null"); return null; } } try { if (pattern != null) { return checkConversionResult(targetType, parse(value, pattern)); } else { return checkConversionResult(targetType, parse(value, this.pattern)); } } catch (final Exception e) { if (useDefault) { return getDefaultAs(targetType); } else { if (e instanceof ConversionException) { throw (ConversionException)e; } throw new ConversionException(e); } } }
/** * * @param rs * @param builder * @throws SQLException */ private void populate(ResultSet rs, Message.Builder builder) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount();// 列个数 String columnLabel = null;// 列名 Object columnValue = null;// 列值 Descriptors.FieldDescriptor fieldDescriptor = null; for (int i = 1; i <= columnCount; i++) { columnLabel = metaData.getColumnLabel(i); columnValue = rs.getObject(i); if (columnValue == null) continue;// 如果为空,继续下一个 fieldDescriptor = descriptor.findFieldByName(columnLabel); if (fieldDescriptor == null) continue;// 如果为空,继续下一个 // 转换为相应的类型 ,会自动将 date 类型转换为long if (fieldDescriptor.getType().equals(FieldDescriptor.Type.ENUM)) { columnValue = fieldDescriptor.getEnumType().findValueByNumber( (int) columnValue); } else { columnValue = ConvertUtils.convert(columnValue, fieldDescriptor .getDefaultValue().getClass()); } builder.setField(fieldDescriptor, columnValue); } }
/** * <p>Initialize other global characteristics of the controller servlet.</p> * * @exception ServletException if we cannot initialize these resources */ protected void initOther() throws ServletException { String value = null; value = getServletConfig().getInitParameter("config"); if (value != null) { config = value; } // Backwards compatibility for form beans of Java wrapper classes // Set to true for strict Struts 1.0 compatibility value = getServletConfig().getInitParameter("convertNull"); if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) { convertNull = true; } if (convertNull) { ConvertUtils.deregister(); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ByteConverter(null), Byte.class); ConvertUtils.register(new CharacterConverter(null), Character.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); } }
public static <T> T copyProperties(Object srcObj, Class<T> toClass) { try { ConvertUtils.register(new DateConverter(null), Date.class); T instance = toClass.newInstance(); BeanUtils.copyProperties(instance, srcObj); return instance; } catch (Exception e) { throw new RuntimeException("拷贝对象属性值异常", e); } }
/** * Get the first parameter value, converted to the requested type. * @param parameters used to extract parameter value from * @param parameterName name of the parameter * @param returnType type of object to return * @return the converted parameter value. Null, if the parameter has no value. * @throws IllegalArgumentException when no conversion for the given returnType is available or if returnType is null. * @throws InvalidArgumentException when conversion to the given type was not possible */ @SuppressWarnings("unchecked") public <T extends Object> T getParameter(Parameters parameters, String parameterName, Class<T> returnType) { if(returnType == null) { throw new IllegalArgumentException("ReturnType cannot be null"); } try { Object result = null; String stringValue = parameters.getParameter(parameterName); if(stringValue != null) { result = ConvertUtils.convert(stringValue, returnType); if(result instanceof String) { // If a string is returned, no converter has been found throw new IllegalArgumentException("Unable to convert parameter to type: " + returnType.getName()); } } return (T) result; } catch(ConversionException ce) { // Conversion failed, wrap in Illegal throw new InvalidArgumentException("Parameter value for '" + parameterName + "' should be a valid " + returnType.getSimpleName()); } }
/** * Get the property value, converted to the requested type. * * @param propertyName name of the parameter * @param type int * @param returnType type of object to return * @return the converted parameter value. Null, if the property has no * value. * @throws IllegalArgumentException when no conversion for the given * returnType is available or if returnType is null. * @throws InvalidArgumentException when conversion to the given type was * not possible due to an error while converting */ @SuppressWarnings("unchecked") public <T extends Object> T getProperty(String propertyName, int type, Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("ReturnType cannot be null"); } try { Object result = null; String stringValue = getProperty(propertyName, type); if (stringValue != null) { result = ConvertUtils.convert(stringValue, returnType); if ((result instanceof String) && (! returnType.equals(String.class))) { // If a string is returned, no converter has been found (for non-String return type) throw new IllegalArgumentException("Unable to convert parameter to type: " + returnType.getName()); } } return (T) result; } catch (ConversionException ce) { // Conversion failed, wrap in Illegal throw new InvalidArgumentException("Query property value for '" + propertyName + "' should be a valid " + returnType.getSimpleName()); } }
@Override public T getParameter(String parameterName, Class<T> clazz) throws InvalidArgumentException { String param = getParameter(parameterName); if (param == null) return null; Object obj = ConvertUtils.convert(param, clazz); if (obj != null && obj.getClass().equals(clazz)) { return (T) obj; } throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID, new Object[] {parameterName}); }
/** * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔 */ public static void registerDateConverter(String patterns) { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(StringUtils.split(patterns, ",")); ConvertUtils.register(dc, Date.class); }
/** * String[] to long[] * * @param str * @return */ public static long[] toLongs(String[] str) { if (str == null || str.length < 1) return new long[] { 0L }; long[] ret = new long[str.length]; ret = (long[]) ConvertUtils.convert(str, long.class); return ret; }