Java tutorial
/** * Copyright (c) 2012-2014 http://www.eryansky.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.eryansky.common.utils; import com.eryansky.common.utils.reflection.ReflectionUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.converters.DateConverter; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; /** * ?. * @author &Eryan eryanwcp@gmail.com * @date 2012-9-5 ?11:12:27 */ public class ConvertUtils extends org.apache.commons.beanutils.ConvertUtils { static { registerDateConverter(); } /** * ????(getter), ??List. * * @param collection ???. * @param propertyName ??????. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static List convertElementPropertyToList(final Collection collection, final String propertyName) { List list = new ArrayList(); try { for (Object obj : collection) { list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } return list; } /** * ????(getter), ??. * * @param collection ???. * @param propertyName ??????. * @param separator . */ @SuppressWarnings({ "rawtypes" }) public static String convertElementPropertyToString(final Collection collection, final String propertyName, final String separator) { List list = convertElementPropertyToList(collection, propertyName); return StringUtils.join(list, separator); } /** * ?. * * @param value ?. * @param toType ?. */ public static Object convertStringToObject(String value, Class<?> toType) { try { return org.apache.commons.beanutils.ConvertUtils.convert(value, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } } /** * Apache BeanUtils?. * * @param value ?. * @param toType ?. */ public static Object convertToObject(String value, Class<?> toType) { try { return convert(value, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } } /** * ?. * * @param values ?. * @param toType ?. */ public static Object convertToObject(String[] values, Class<?> toType) { try { return convert(values, toType); } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } } /** * Converter?: yyyy-MM-dd yyyy-MM-dd HH:mm:ss */ private static void registerDateConverter() { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class); } }