public final class ConvertUtil extends Object
ConvertUtils
几个方法的区别:
方法 说明 ConvertUtils.convert(Object)
将指定的value转成string.
如果value是array,将会返回数组第一个元素转成string.
将会使用注册的java.lang.String
Converter
,
允许应用定制 Object->
String conversions(默认使用简单的使用 toString())
seeConvertUtilsBean.convert(Object)
ConvertUtils.convert(String, Class)
将String value转成 指定Class 类型的对象 (如果可能),否则返回string.
seeConvertUtilsBean.convert(String, Class)
ConvertUtils.convert(String[], Class)
将数组转成指定class类型的对象.
如果指定的Class类型是数组类型,那么返回值的类型将是数组的类型.否则将会构造一个指定类型的数组返回.
seeConvertUtilsBean.convert(String[], Class)
seetoArray(String[], Class)
ConvertUtils.convert(Object, Class)
将value转成指定Class类型的对象,如果Class的转换器没有注册,那么传入的value原样返回.
seeConvertUtilsBean.convert(Object, Class)
seeconvert(Object, Class)
standard Converter
instances are provided for all of the following destination Classes:
字段 说明 BigDecimal
no default value BigInteger
no default value boolean and Boolean
default to false byte and Byte
default to zero char and Character
default to a space Class
no default value double and Double
default to zero float and Float
default to zero int and Integer
default to zero long and Long
default to zero short and Short
default to zero String
default to null File
no default value URL
no default value Date
no default value Time
no default value Timestamp
no default value
ConvertUtils
,
AbstractConverter.handleMissing(Class)
,
LocaleConvertUtils
Modifier and Type | Method and Description |
---|---|
static <T> T |
convert(Object toBeConvertedValue,
Class<T> targetType)
将
toBeConvertedValue 转成指定 targetType 类型的对象. |
static void |
registerSimpleDateLocaleConverter(String pattern)
Register simple date locale converter.
|
static void |
registerStandardDefaultNull()
Register standard default null.
|
static <T> T[] |
toArray(Collection<T> collection,
Class<T> arrayComponentType)
将集合
collection 转成数组. |
static <T> T[] |
toArray(String[] toBeConvertedValue,
Class<T> targetType)
将字符串数组
toBeConvertedValue 转成指定类型 targetType 的数组. |
static <T> T[] |
toArray(T... arrays)
将动态数组转成数组.
|
static BigDecimal |
toBigDecimal(Object toBeConvertedValue)
将
toBeConvertedValue 转换成 BigDecimal . |
static Boolean |
toBoolean(Object toBeConvertedValue)
将
toBeConvertedValue 转换成 Boolean 类型. |
static <T> Enumeration<T> |
toEnumeration(Collection<T> collection)
将集合
collection 转成Enumeration . |
static Integer |
toInteger(Object toBeConvertedValue)
将
toBeConvertedValue 转换成 Integer 类型. |
static Integer |
toInteger(Object toBeConvertedValue,
Integer defaultValue)
|
static Integer[] |
toIntegers(Object toBeConvertedValue)
将
toBeConvertedValue 转成Integer 数组. |
static <T> Iterator<T> |
toIterator(Object toBeConvertedValue)
将
toBeConvertedValue 转成Iterator 类型. |
static <T> List<T> |
toList(Collection<T> collection)
将 集合
collection 转成 list. |
static <T> List<T> |
toList(Enumeration<T> enumeration)
将枚举
enumeration 转成 List . |
static <T> List<T> |
toList(T... arrays)
数组转成 (
ArrayList ). |
static Locale |
toLocale(Object locale)
将对象转成
Locale . |
static Long |
toLong(Object toBeConvertedValue)
将
toBeConvertedValue 转换成 Long 类型. |
static Long[] |
toLongs(Object toBeConvertedValue)
将
toBeConvertedValue 转成Long 数组. |
static <V,K,E extends Map.Entry<K,V>> |
toMap(Collection<E> mapEntryCollection)
将
mapEntryCollection 转成map (LinkedHashMap ). |
static <K,V> Map<K,V> |
toMap(K key,
V value)
将
key 和 value 直接转成map. |
static <K,V> Map<K,V> |
toMap(K key1,
V value1,
K key2,
V value2)
将
key1 和 value1 /key2 和 value2 直接转成map. |
static <K,V,I,J> Map<I,J> |
toMap(Map<K,V> inputMap,
Class<I> keyTargetType,
Class<J> valueTargetType)
将诸如 Map
<String, String> 类型转成 Map<Integer, Integer> 类型. |
static <K,V,J> Map<K,J> |
toMap(Map<K,V> inputMap,
Class<J> valueTargetType)
将诸如 Map
<String, String> 类型转成 Map<String, Integer> 类型. |
static <K,V,I,J> Map<I,J> |
toMap(Map<K,V> inputMap,
Transformer<K,I> keyTransformer,
Transformer<V,J> valueTransformer)
将诸如 Map
<String, String> 类型转成 Map<Integer, Integer> 类型. |
static Map<String,String> |
toMap(Properties properties)
将
properties 转换成map. |
static <V,K> Map<K,V> |
toMapUseEntrys(Map.Entry<K,V>... mapEntrys)
将
Map.Entry 数组转成map (LinkedHashMap ). |
static Properties |
toProperties(Map<String,String> map)
将map转成
Properties . |
static <T> Set<T> |
toSet(T... arrays)
数组转成 Set (
LinkedHashSet ). |
static String |
toString(Collection<?> collection,
String connector)
将集合
collection 使用拼接 connector 拼接成字符串. |
static String |
toString(Collection<?> collection,
ToStringConfig toStringConfig)
将集合
collection 使用拼接配置 toStringConfig 拼接成字符串. |
static String |
toString(Object toBeConvertedValue)
把对象
toBeConvertedValue 转换成字符串. |
static String |
toString(Object[] arrays,
String connector)
将数组
arrays 通过 connector 拼接成字符串. |
static String |
toString(Object[] arrays,
ToStringConfig toStringConfig)
将数组
arrays 通过ToStringConfig 拼接成字符串. |
static String[] |
toStrings(Object toBeConvertedValue)
将
toBeConvertedValue 转成String 数组. |
public static void registerStandardDefaultNull()
public static void registerSimpleDateLocaleConverter(String pattern)
pattern
- the patternpublic static Boolean toBoolean(Object toBeConvertedValue)
toBeConvertedValue
转换成 Boolean
类型.
ConvertUtil.toBoolean(null) = null ConvertUtil.toBoolean(1L) = true ConvertUtil.toBoolean("1") = true ConvertUtil.toBoolean("9") = null ConvertUtil.toBoolean("1,2,3") = null
- 如果 "true", "yes", "y", "on", "1" (忽视大小写), 返回 true
- 如果 "false", "no", "n", "off", "0" (忽视大小写), 返回 false
- 其他抛出 conversionException, 但是在
handleError(Class, Object, Throwable)
方法里面返回默认值 是 null你也可以调用
BooleanConverter(String[], String[], Object)
设置 trueStrings 和 falseStrings
Boolean.parseBoolean(String)
的区别:
Boolean.parseBoolean(String)
,仅当(String != null) 并且 String.equalsIgnoreCase("true")
返回 true
toBeConvertedValue
- objecttoBeConvertedValue
是null,返回nullconvert(Object, Class)
,
BooleanConverter
,
BooleanUtils
,
Boolean.parseBoolean(String)
public static Integer toInteger(Object toBeConvertedValue)
toBeConvertedValue
转换成 Integer
类型.
ConvertUtil.toInteger(null) = null ConvertUtil.toInteger("aaaa") = null ConvertUtil.toInteger(8L) = 8 ConvertUtil.toInteger("8") = 8 ConvertUtil.toInteger(new BigDecimal("8")) = 8如果传入的参数
toBeConvertedValue
是 数组,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
L227:ConvertUtil.toInteger(new String[] { "1", "2", "3" }) = 1如果传入的参数
toBeConvertedValue
是 集合,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
Line234:ConvertUtil.toInteger(toList("1", "2")) = 1
该方法非常适用 获取request请求的分页参数
原来的写法:
public static Integer getCurrentPageNo(HttpServletRequest request,String pageParamName){ String pageNoString = RequestUtil.getParameter(request, pageParamName); try{ int pageNo = Integer.parseInt(pageNoString); return pageNo; }catch (Exception e){ LOGGER.error(e.getClass().getName(), e); } return 1; // 不带这个参数或者转换异常返回1 }
现在可以更改成:
public static Integer getCurrentPageNo(HttpServletRequest request,String pageParamName){ String pageNoString = RequestUtil.getParameter(request, pageParamName); Integer pageNo = ConvertUtil.toInteger(pageNoString); return null == pageNo ? 1 : pageNo; }当然对于这种场景,最快捷的:调用支持默认值的
toInteger(Object, Integer)
方法public static Integer getCurrentPageNo(HttpServletRequest request,String pageParamName){ String pageNoString = RequestUtil.getParameter(request, pageParamName); return ConvertUtil.toInteger(pageNoString, 1); }
toBeConvertedValue
- 值toBeConvertedValue
是null,返回 nulltoBeConvertedValue
是 数组,那么取第一个元素进行转换toBeConvertedValue
是 集合,那么取第一个元素进行转换IntegerConverter
,
NumberUtils.toInt(String)
,
toInteger(Object, Integer)
public static Integer toInteger(Object toBeConvertedValue, Integer defaultValue)
toBeConvertedValue
转换成 Integer
类型,如果转换不了返回默认值 defaultValue
.
ConvertUtil.toInteger(null,null) = null ConvertUtil.toInteger(null,1) = 1 ConvertUtil.toInteger("aaaa",1) = 1 ConvertUtil.toInteger(8L,1) = 8 ConvertUtil.toInteger("8",1) = 8 ConvertUtil.toInteger(new BigDecimal("8"),1) = 8如果传入的参数
toBeConvertedValue
是 数组,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
L227:ConvertUtil.toInteger(new String[] { "1", "2", "3" }, 8) = 1如果传入的参数
toBeConvertedValue
是 集合,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
Line234:ConvertUtil.toInteger(toList("1", "2"), 8) = 1
该方法非常适用 获取request请求的分页参数
原来的写法:public static Integer getCurrentPageNo(HttpServletRequest request,String pageParamName){ String pageNoString = RequestUtil.getParameter(request, pageParamName); try{ int pageNo = Integer.parseInt(pageNoString); return pageNo; }catch (Exception e){ LOGGER.error(e.getClass().getName(), e); } return 1; // 不带这个参数或者转换异常返回1 }
现在可以更改成:public static Integer getCurrentPageNo(HttpServletRequest request,String pageParamName){ String pageNoString = RequestUtil.getParameter(request, pageParamName); return ConvertUtil.toInteger(pageNoString, 1); }
toBeConvertedValue
- 值defaultValue
- 默认值toBeConvertedValue
是null,返回 defaultValue
toBeConvertedValue
是 数组,那么取第一个元素进行转换toBeConvertedValue
是 集合,那么取第一个元素进行转换defaultValue
IntegerConverter
,
ObjectUtils.defaultIfNull(Object, Object)
public static Long toLong(Object toBeConvertedValue)
toBeConvertedValue
转换成 Long
类型.
ConvertUtil.toLong(null) = null ConvertUtil.toLong("aaaa") = null ConvertUtil.toLong(8) = 8L ConvertUtil.toLong("8") = 8L ConvertUtil.toLong(new BigDecimal("8")) = 8L如果传入的参数
toBeConvertedValue
是 数组,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
L227:ConvertUtil.toLong(new String[] { "1", "2", "3" }) = 1L如果传入的参数
toBeConvertedValue
是 集合,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
Line234:ConvertUtil.toLong(toList("1", "2")) = 1L
toBeConvertedValue
- 包含数字的对象.toBeConvertedValue
是null,返回 nulltoBeConvertedValue
是 数组,那么取第一个元素进行转换toBeConvertedValue
是 集合,那么取第一个元素进行转换convert(Object, Class)
,
LongConverter
,
NumberUtils.toLong(String)
public static BigDecimal toBigDecimal(Object toBeConvertedValue)
toBeConvertedValue
转换成 BigDecimal
.
ConvertUtil.toBigDecimal(null) = null ConvertUtil.toBigDecimal("aaaa") = null ConvertUtil.toBigDecimal(8) = BigDecimal.valueOf(8) ConvertUtil.toBigDecimal("8") = BigDecimal.valueOf(8) ConvertUtil.toBigDecimal(new BigDecimal("8")) = BigDecimal.valueOf(8)如果传入的参数
toBeConvertedValue
是 数组,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
L227:ConvertUtil.toBigDecimal(new String[] { "1", "2", "3" }) = BigDecimal.valueOf(1)如果传入的参数
toBeConvertedValue
是 集合,那么取第一个元素进行转换,参见AbstractConverter.convertArray(Object)
Line234:ConvertUtil.toBigDecimal(toList("1", "2")) = BigDecimal.valueOf(1)
Double
转成 BigDecimal
注意点:推荐使用
BigDecimal.valueOf(double)
,不建议使用new BigDecimal(double)
,参见 JDK API
new BigDecimal(0.1) ====> 0.1000000000000000055511151231257827021181583404541015625
BigDecimal.valueOf(0.1) ====> 0.1
本方法底层调用的是
NumberConverter#toNumber(Class, Class, Number)
,正确的处理了Double
转成BigDecimal
toBeConvertedValue
- 值toBeConvertedValue
是null,返回 nulltoBeConvertedValue
是 数组,那么取第一个元素进行转换toBeConvertedValue
是 集合,那么取第一个元素进行转换convert(Object, Class)
,
NumberConverter.toNumber(Class, Class, Number)
,
BigDecimalConverter
public static Integer[] toIntegers(Object toBeConvertedValue)
toBeConvertedValue
转成Integer
数组.
核心实现,参见
ArrayConverter.convertToType(Class, Object)
- 如果参数
toBeConvertedValue
是数组
或者Collection
参见
ArrayConverter#convertToType(Class,Object)
会构造一个Integer
数组,长度就是toBeConvertedValue
的大小或者长度,然后迭代toBeConvertedValue
依次逐个进行转换示例:
ConvertUtil.toIntegers(new String[] { "1", "2", "3" }) = [1,2,3] ConvertUtil.toIntegers(toList("1", "2", "3")) = [1,2,3]- 如果参数
toBeConvertedValue
不是数组
也不是Collection
那么首先会调用
ArrayConverter.convertToCollection(Class, Object)
将toBeConvertedValue
转成集合,转换逻辑参见ArrayConverter.convertToCollection(Class, Object)
:
- 如果
toBeConvertedValue
是Number
,Boolean
或者Date
,那么构造只有一个toBeConvertedValue
元素的 List返回.- 其他类型将转成字符串,然后调用
ArrayConverter.parseElements(Class, String)
转成list.具体转换逻辑为:
- 字符串期望是一个逗号分隔的字符串.
- 字符串可以被'{' 开头 和 '}'结尾的分隔符包裹,程序内部会自动截取.
- 会去除前后空白.
- Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are valid.
得到list之后,会构造一个
Integer
数组,长度就是toBeConvertedValue
的大小或者长度,然后迭代toBeConvertedValue
依次逐个进行转换示例:
ConvertUtil.toIntegers("1,2,3") = new Integer[] { 1, 2, 3 } ConvertUtil.toIntegers("{1,2,3}") = new Integer[] { 1, 2, 3 } ConvertUtil.toIntegers("{ 1 ,2,3}") = new Integer[] { 1, 2, 3 } ConvertUtil.toIntegers("1,2, 3") = new Integer[] { 1, 2, 3 } ConvertUtil.toIntegers("1,2 , 3") = new Integer[] { 1, 2, 3 }每个元素转换成 Integer的时候,会调用
NumberConverter.convertToType(Class, Object)
,具体的规则是:
- 1.如果 元素是 Number类型
- 那么会调用
NumberConverter.toNumber(Class, Class, Number)
- 2.如果 元素是 Boolean类型
- 那么 true被转成1,false 转成 0
- 3.其他情况
- 将元素转成字符串,并trim,再进行转换
- 4.元素是null的情况
- 如果有元素是null,那么会调用
AbstractConverter.convert(Class, Object)
,会调用AbstractConverter.handleMissing(Class)
方法,没有默认值的话,会抛出异常,然后catch之后返回 empty Integer 数组示例:
ConvertUtil.toIntegers(toList("1", "2", " 3")) = new Integer[] { 1, 2, 3 } ConvertUtil.toIntegers(toArray(true, false, false)) = new Integer[] { 1, 0, 0 } ConvertUtil.toIntegers(new String[] { "1", null, "2", "3" }) = new Integer[] {}
toBeConvertedValue
- 需要被转换的值toBeConvertedValue
是null,返回 nullconvert(Object, Class)
,
ArrayConverter
public static Long[] toLongs(Object toBeConvertedValue)
toBeConvertedValue
转成Long 数组.
核心实现,参见
ArrayConverter.convertToType(Class, Object)
- 如果参数
toBeConvertedValue
是数组
或者Collection
参见
ArrayConverter#convertToType(Class,Object)
会构造一个Long
数组,长度就是toBeConvertedValue
的大小或者长度,然后迭代toBeConvertedValue
依次逐个进行转换示例:
ConvertUtil.toLongs(new String[] { "1", "2", "3" } = [1L,2L,3L] ConvertUtil.toLongs(toList("1", "2", "3")) = [1L,2L,3L]- 如果参数
toBeConvertedValue
不是数组
也不是Collection
那么首先会调用
ArrayConverter.convertToCollection(Class, Object)
将toBeConvertedValue
转成集合,转换逻辑参见ArrayConverter.convertToCollection(Class, Object)
:
- 如果
toBeConvertedValue
是Number
,Boolean
或者Date
,那么构造只有一个toBeConvertedValue
元素的 List返回.- 其他类型将转成字符串,然后调用
ArrayConverter.parseElements(Class, String)
转成list.具体转换逻辑为:
- 字符串期望是一个逗号分隔的字符串.
- 字符串可以被'{' 开头 和 '}'结尾的分隔符包裹,程序内部会自动截取.
- 会去除前后空白.
- Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are valid.
得到list之后,会构造一个
Long
数组,长度就是toBeConvertedValue
的大小或者长度,然后迭代toBeConvertedValue
依次逐个进行转换示例:
ConvertUtil.toLongs("1,2,3") = new Long[] { 1L, 2L, 3L } ConvertUtil.toLongs("{1,2,3}") = new Long[] { 1L, 2L, 3L } ConvertUtil.toLongs("{ 1 ,2,3}") = new Long[] { 1L, 2L, 3L } ConvertUtil.toLongs("1,2, 3") = new Long[] { 1L, 2L, 3L } ConvertUtil.toLongs("1,2 , 3") = new Long[] { 1L, 2L, 3L }每个元素转换成 Integer的时候,会调用
NumberConverter.convertToType(Class, Object)
,具体的规则是:
- 1.如果 元素是 Number类型
- 那么会调用
NumberConverter.toNumber(Class, Class, Number)
- 2.如果 元素是 Boolean类型
- 那么 true被转成1L,false 转成 0L
- 3.其他情况
- 将元素转成字符串,并trim,再进行转换
- 4.元素是null的情况
- 如果有元素是null,那么会调用
AbstractConverter.convert(Class, Object)
,会调用AbstractConverter.handleMissing(Class)
方法,没有默认值的话,会抛出异常,然后catch之后返回 empty Integer 数组示例:
ConvertUtil.toLongs(toList("1", "2", " 3")) = new Long[] { 1L, 2L, 3L } ConvertUtil.toLongs(toArray(true, false, false)) = new Long[] { 1L, 0L, 0L } ConvertUtil.toLongs(new String[] { "1", null, "2", "3" }) = new Long[] {}
protected long[] getOrderIdLongs(String orderIds){ // 确认交易时候插入数据库的时候,不应该会出现空的情况 String[] orderIdArray = orderIds.split(","); int orderLength = orderIdArray.length; long[] ids = new long[orderLength]; for (int i = 0, j = orderLength; i可以重构成:<
j; ++i){ ids[i] = Long.parseLong(orderIdArray[i]); } return ids; }protected long[] getOrderIdLongs(String orderIds){ return toLongs(orderIds); }
toBeConvertedValue
- the to be converted valuetoBeConvertedValue
是null,返回 nullConvertUtils.convert(Object, Class)
,
ArrayConverter
,
convert(Object, Class)
public static String toString(Object toBeConvertedValue)
toBeConvertedValue
转换成字符串.
ConvertUtil.toString(1) = "1" ConvertUtil.toString(toLong(8L)) = "8" ConvertUtil.toString(toBigDecimal(1.0)) = "1.00" ConvertUtil.toString(new Double(1.0)) = "1.00" ConvertUtil.toString(new Float(1.0)) = "1.00" ConvertUtil.toString(toList("张飞", "关羽", "", "赵云")) = "张飞,关羽,,赵云" ConvertUtil.toString(toArray("张飞", "关羽", "", "赵云")) = "张飞,关羽,,赵云" ConvertUtil.toString(toArray(null, "关羽", "", "赵云")) = ",关羽,,赵云"
toBeConvertedValue
- 参数值toBeConvertedValue
是null,返回 nulltoBeConvertedValue
是 CharSequence
,直接 toString返回toBeConvertedValue
是 数组,那么调用 toString(Object[], String)
toBeConvertedValue
是 Collection
,那么调用 toString(Object[], String)
toBeConvertedValue
是 Date
,那么返回 DatePattern.COMMON_DATE_AND_TIME
格式字符串toBeConvertedValue
是 BigDecimal
或者是Float
或者是 Double
,那么返回
NumberPattern.TWO_DECIMAL_POINTS
2 位小数点格式字符串convert(Object, Class)
ToStringHandler.toStringValue(Object)
ArrayConverter.convertToString(Object)
,
ConvertUtils.convert(Object)
,
ConvertUtilsBean.convert(Object)
,
StringConverter
,
Arrays.toString(Object[])
public static String toString(Collection<?> collection, String connector)
collection
使用拼接 connector
拼接成字符串.
List输出:<String>
list = com.feilong.core.bean.ConvertUtil.toList("feilong", "", "xinge"); ConvertUtil.toString(list,",");feilong,,xinge
你还可以使用这个方法来将集合换行输出,比如:List输出:<String>
list = toList("飞龙", "小金", "四金", "金金金金"); LOGGER.debug(ConvertUtil.toString(list, System.lineSeparator()));飞龙 小金 四金 金金金金
- 如果有元素是null,使用
StringUtils.EMPTY
替代拼接- 最后一个元素后面不拼接拼接符
collection
- 集合,建议元素泛型不要使用自定义的对象(比如UserCommand等),因为这个方法是迭代collection,拿每个元素的字符串格式 进行拼接connector
- the connectorcollection
是null或者empty,返回 StringUtils.EMPTY
IteratorUtils.toString(Iterator)
,
StringUtils.join(Iterable, String)
public static String toString(Object[] arrays, String connector)
arrays
通过 connector
拼接成字符串.
ConvertUtil.toString(null,",") = "" ConvertUtil.toString(toArray(),",") = "" ConvertUtil.toString(toArray("a","b"),",") = "a,b" Integer[] array3 = { 2, null, 1, null }; ConvertUtil.toString(array3,",") = "2,,1,"
需要先使用下列的方式先转成包装类型数组
- 如果有元素是null,使用
StringUtils.EMPTY
替代拼接- 最后一个元素后面不拼接拼接符
arrays
- 支持包装类型,不直接支持原始类型connector
- the connectorarrays
是null 或者Empty,返回 StringUtils.EMPTY
ToStringStyle
,
StringUtils.join(Object[], String)
public static String toString(Collection<?> collection, ToStringConfig toStringConfig)
collection
使用拼接配置 toStringConfig 拼接成字符串.
List输出:<String>
list = new ArrayList<>
(); list.add("feilong"); list.add(""); list.add("xinge"); ToStringConfig toStringConfig = new ToStringConfig(","); toStringConfig.setIsJoinNullOrEmpty(false); ConvertUtil.toString(list,toStringConfig);feilong,xinge
你还可以使用这个方法来将集合换行输出,比如:List输出:<String>
list = toList("飞龙", "小金", "四金", "金金金金"); ToStringConfig toStringConfig = new ToStringConfig(System.lineSeparator()); LOGGER.debug(ConvertUtil.toString(list, toStringConfig));飞龙 小金 四金 金金金金
ToStringConfig
:如果参数
toStringConfig
是null,则使用默认的规则:
- 连接符使用
ToStringConfig.DEFAULT_CONNECTOR
- 拼接null或者empty元素
- 如果元素是null,使用
StringUtils.EMPTY
替代拼接- 最后一个元素后面不拼接拼接符
ToStringConfig
prefix(since 1.12.9):如果你需要在拼接每个元素的时候,给每个元素加上前缀, 比如 solr 查询, 运营人员配置了一些商品code ,
1533312,1533292,1785442
, 此时你需要生成code:1533312 OR code:1533292 OR code:1785442
字符串去solr 中查询此时你可以这么调用
String configItemCodes = "1533312,1533292,1785442"; String[] tokenizeToStringArray = StringUtil.tokenizeToStringArray(configItemCodes, ","); List返回:<String>
list = toList(tokenizeToStringArray); ToStringConfig toStringConfig = new ToStringConfig(" OR ", false, "code:"); String string = ConvertUtil.toString(list, toStringConfig);code:1533312 OR code:1533292 OR code:1785442
collection
- 集合,建议元素泛型不要使用自定义的对象(比如UserCommand等),因为这个方法是迭代collection,拿每个元素的字符串格式 进行拼接toStringConfig
- 连接字符串 实体collection
是null或者empty,返回 StringUtils.EMPTY
toStringConfig
是null,使用默认 ToStringConfig.DEFAULT_CONNECTOR
以及 joinNullOrEmpty 进行连接IteratorUtils.toString(Iterator)
,
StringUtils.join(Iterable, String)
public static String toString(Object[] arrays, ToStringConfig toStringConfig)
arrays
通过ToStringConfig
拼接成字符串.
ConvertUtil.toString(toArray("a","b"),new ToStringConfig()) = "a,b" ToStringConfig toStringConfig=new ToStringConfig(","); toStringConfig.setIsJoinNullOrEmpty(false); ConvertUtil.toString(toArray("a","b",null),new ToStringConfig()) = "a,b"
需要先使用下列的方式先转成包装类型数组
ToStringConfig
:如果参数
toStringConfig
是null,则使用默认的规则:
- 连接符使用
ToStringConfig.DEFAULT_CONNECTOR
- 拼接null或者empty元素
- 如果元素是null,使用
StringUtils.EMPTY
替代拼接- 最后一个元素后面不拼接拼接符
ToStringConfig
prefix(since 1.12.9):如果你需要在拼接每个元素的时候,给每个元素加上前缀, 比如 solr 查询, 运营人员配置了一些商品code ,
1533312,1533292,1785442
, 此时你需要生成code:1533312 OR code:1533292 OR code:1785442
字符串去solr 中查询此时你可以这么调用
String configItemCodes = "1533312,1533292,1785442"; String返回:[]
tokenizeToStringArray = StringUtil.tokenizeToStringArray(configItemCodes, ","); ToStringConfig toStringConfig = new ToStringConfig(" OR ", false, "code:"); String string = ConvertUtil.toString(tokenizeToStringArray, toStringConfig);code:1533312 OR code:1533292 OR code:1785442
arrays
- 支持包装类型,不直接支持原始类型toStringConfig
- the to string configarrays
是null 或者Empty,返回 StringUtils.EMPTY
toStringConfig
是null,使用默认 ToStringConfig.DEFAULT_CONNECTOR
以及 joinNullOrEmpty 进行连接ToStringConfig.getConnector()
ToStringStyle
,
StringUtils.join(Object[], String)
,
StringUtils.join(Iterable, String)
public static <T> Enumeration<T> toEnumeration(Collection<T> collection)
collection
转成Enumeration
.
- 一般情况,你可能不需要这个方法,不过在一些API的时候,需要
Enumeration
参数,此时调用这个方法来进行转换会比较方便
ConvertUtil.toEnumeration(null) = Collections.emptyEnumeration()
T
- the generic typecollection
- 集合collection
是null,返回 Collections.emptyEnumeration()
Collections.enumeration(Collection)
Collections.enumeration(Collection)
public static <K,V> Map<K,V> toMap(K key, V value)
key
和 value
直接转成map.
- 返回是的是
LinkedHashMap
非常适合单key的场景,比如
Map上面的3行代码可以重写成<String, String>
paramMap = newHashMap(); paramMap.put("name", "jinxin"); request.setParamMap(paramMap);request.setParamMap(toMap("name", "jinxin"));一行代码就搞定了,很简洁,有木有~~
LOGGER.debug(JsonUtil.format(ConvertUtil.toMap("张飞", "丈八蛇矛")));返回:{"张飞": "丈八蛇矛"}
对于以下代码:
private List可以重构成:<ShopCommand>
loadShopCommandList(){ Map<String, Object>
paraMap = newHashMap(); paraMap.put("orgTypeId", OrgType.ID_SHOP_TYPE); return shopCommandDao.findShopListByOrgaTypeId(paraMap); }private List<ShopCommand>
loadShopCommandList(){ Map<String, Object>
paraMap = ConvertUtil.toMap("orgTypeId", (Object) OrgType.ID_SHOP_TYPE); return shopCommandDao.findShopListByOrgaTypeId(paraMap); }
K
- the key typeV
- the value typekey
- the keyvalue
- the valuekey
和 value
直接转成mapArrayUtils.toMap(Object[])
,
Collections.singletonMap(Object, Object)
,
"com.google.common.collect.ImmutableMap#of(K, V)"public static <K,V> Map<K,V> toMap(K key1, V value1, K key2, V value2)
key1
和 value1
/key2
和 value2
直接转成map.
- 返回是的是
LinkedHashMap
非常适合2个key的场景,比如
Map上面的3行代码可以重写成<String, String>
paramMap =newHashMap(); paramMap.put("name", "jinxin"); paramMap.put("age", "18"); request.setParamMap(paramMap);request.setParamMap(toMap("name", "jinxin", "age", "18"));一行代码就搞定了,很简洁,有木有~~
对于以下代码:
Map可以重构成:<String, Long>
map = newHashMap(); map.put("itemId", itemId); map.put("memberId", memberId); memberFavoritesDao.findMemberFavoritesByMemberIdAndItemId(map);Map<String, Long>
map = ConvertUtil.toMap("itemId", itemId, "memberId", memberId); memberFavoritesDao.findMemberFavoritesByMemberIdAndItemId(map);
K
- the key typeV
- the value typekey1
- the key 1value1
- the value 1key2
- the key 2value2
- the value 2key1
和 value1
/key2
和 value2
直接转成mapArrayUtils.toMap(Object[])
,
Collections.singletonMap(Object, Object)
,
"com.google.common.collect.ImmutableMap#of(K, V)"public static Map<String,String> toMap(Properties properties)
properties
转换成map.
Properties properties = new Properties(); properties.setProperty("name", "feilong"); properties.setProperty("age", "18"); properties.setProperty("country", "china"); LOGGER.debug(JsonUtil.format(toMap(properties)));返回:{ "age": "18", "country": "china", "name": "feilong" }
- 返回的map 经过了
SortUtil.sortMapByKeyAsc(Map)
排序处理,方便输出日志
Properties
Properties 是 Map的实现类 ,其 key和value 是String 类型.
因此Properties 可以强制转换成map
properties
- the propertiesproperties
是null或者empty,返回 Collections.emptyMap()
MapUtils.toProperties(Map)
public static <K,V,J> Map<K,J> toMap(Map<K,V> inputMap, Class<J> valueTargetType)
<String, String>
类型转成 Map<String, Integer>
类型.
- 适合只是简单的将key value类型转换,而不需要自己再构建Transformer,再去调用
toMap(Map, Transformer, Transformer)
,简化操作- 返回的是
LinkedHashMap
,顺序依照入参 inputMap- 返回的是新的map,原来的
toMap
参数不受影响- 也支持诸如 Map
<String, Integer>
转 Map<String, String>
(key和value 使用不同的转换器)- 也支持诸如 Map
<String, String>
转 Map<String, Integer[]>
(单值转数组)- 也支持诸如 Map
<String[], String[]>
转 Map<String[], Long[]>
(数组转数组)
场景1: 将Map
<String, String>
转 Map<String, Integer>
类型Map返回:<String, String>
map = toMap("1", "2"); Map<String, Integer>
returnMap = toMap(map, Integer.class); // 输出测试 for (Map.Entry<String, Integer>
entry : returnMap.entrySet()){ String key = entry.getKey(); Integer value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:["1"],value:[2]
场景2: Map
<String, String>
转 Map<String, Integer[]>
Map返回:<String, String>
map = toMap("1", "2,2"); //key和value转成不同的类型 Map<String, Integer[]>
returnMap = toMap(map, Integer[].class); // 输出测试 for (Map.Entry<String, Integer[]>
entry : returnMap.entrySet()){ String key = entry.getKey(); Integer[] value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:["1"],value:[[2, 2]]
场景3: Map
<String[], String[]>
转 Map<String[], Long[]>
Map<String[], String[]>
map = toMap(toArray("1"), toArray("2", "8")); //key和value转成不同的类型 Map<String[], Long[]>
returnMap = toMap(map, Long[].class); assertThat(returnMap, allOf(hasEntry(toArray("1"), toArray(2L, 8L))));
K
- the key typeV
- the value typeJ
- 返回的map ,value的类型inputMap
- the input mapvalueTargetType
- value 需要转换成什么类型,类型可以和原map的类型相同或者可以设置为null,均表示返回的map使用inputMap
原样的value
,不会进行类型转换inputMap
是null或者empty,返回 Collections.emptyMap()
valueTargetType
是null,那么value 直接使用inputMap
的 valuetoMap(Map, Class, Class)
,
issues661public static <K,V,I,J> Map<I,J> toMap(Map<K,V> inputMap, Class<I> keyTargetType, Class<J> valueTargetType)
<String, String>
类型转成 Map<Integer, Integer>
类型.
- 适合只是简单的将key value类型转换,而不需要自己再构建Transformer,再去调用
toMap(Map, Transformer, Transformer)
,简化操作- 返回的是
LinkedHashMap
,顺序依照入参 inputMap- 返回的是新的map,原来的
toMap
参数不受影响- 也支持诸如 Map
<String, Integer>
转 Map<Integer, String>
(key和value 使用不同的转换器)- 也支持诸如 Map
<String, String>
转 Map<Integer, Integer[]>
(单值转数组)- 也支持诸如 Map
<String[], String[]>
转 Map<Integer[], Long[]>
(数组转数组)
场景1: 将Map
<String, String>
转 Map<Integer, Integer>
类型Map返回:<String, String>
map = toMap("1", "2"); Map<Integer, Integer>
returnMap = toMap(map, Integer.class, Integer.class); // 输出测试 for (Map.Entry<Integer, Integer>
entry : returnMap.entrySet()){ Integer key = entry.getKey(); Integer value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:[1],value:[2]
场景2: Map
<String, String>
转 Map<Integer, Integer[]>
Map返回:<String, String>
map = toMap("1", "2,2"); //key和value转成不同的类型 Map<Integer, Integer[]>
returnMap = toMap(map, Integer.class, Integer[].class); // 输出测试 for (Map.Entry<Integer, Integer[]>
entry : returnMap.entrySet()){ Integer key = entry.getKey(); Integer[] value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:[1],value:[[2, 2]]
场景3: Map
<String[], String[]>
转 Map<Integer[], Long[]>
Map<String[], String[]>
map = toMap(toArray("1"), toArray("2", "8")); //key和value转成不同的类型 Map<Integer[], Long[]>
returnMap = toMap(map, Integer[].class, Long[].class); assertThat(returnMap, allOf(hasEntry(toArray(1), toArray(2L, 8L))));
K
- the key typeV
- the value typeI
- 返回的map ,key的类型J
- 返回的map ,value的类型inputMap
- the input mapkeyTargetType
- key需要转换成什么类型,类型可以和原map的类型相同或者可以设置为null,均表示返回的map使用inputMap
原样的key
,不会进行类型转换valueTargetType
- value 需要转换成什么类型,类型可以和原map的类型相同或者可以设置为null,均表示返回的map使用inputMap
原样的value
,不会进行类型转换inputMap
是null或者empty,返回 Collections.emptyMap()
keyTargetType
是null,那么key直接使用inputMap
的keyvalueTargetType
是null,那么value 直接使用inputMap
的 valuetoMap(Map, Transformer, Transformer)
,
issues497public static <K,V,I,J> Map<I,J> toMap(Map<K,V> inputMap, Transformer<K,I> keyTransformer, Transformer<V,J> valueTransformer)
<String, String>
类型转成 Map<Integer, Integer>
类型.
- 适合复杂的类型转换场景,如果只是简单的类型转换,你可以直接调用
toMap(Map, Class, Class)
- 返回的是
LinkedHashMap
,顺序依照入参 inputMap- 返回的是新的map,原来的
toMap
参数不受影响- 也支持诸如 Map
<String, Integer>
转 Map<Integer, String>
(key和value 使用不同的转换器)- 也支持诸如 Map
<String, String>
转 Map<Integer, Integer[]>
(单值转数组)- 也支持诸如 Map
<String[], String[]>
转 Map<Integer[], Long[]>
(数组转数组)
场景1: 将Map
<String, String>
转 Map<Integer, Integer>
类型Map返回:<String, String>
map = toMap("1", "2"); //key和value 都转成integer 使用相同的转换器 Transformer<String, Integer>
transformer = new SimpleClassTransformer<>
(Integer.class); Map<Integer, Integer>
returnMap = toMap(map, transformer, transformer); // 输出测试 for (Map.Entry<Integer, Integer>
entry : returnMap.entrySet()){ Integer key = entry.getKey(); Integer value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:[1],value:[2]
场景2: Map
<String, String>
转 Map<Integer, Integer[]>
Map返回:<String, String>
map = toMap("1", "2,2"); Transformer<String, Integer>
keyTransformer = new SimpleClassTransformer<>
(Integer.class); Transformer<String, Integer[]>
valueTransformer = new SimpleClassTransformer<>
(Integer[].class); //key和value转成不同的类型 Map<Integer, Integer[]>
returnMap = toMap(map, keyTransformer, valueTransformer); // 输出测试 for (Map.Entry<Integer, Integer[]>
entry : returnMap.entrySet()){ Integer key = entry.getKey(); Integer[] value = entry.getValue(); LOGGER.debug("key:[{}],value:[{}]", key, value); }key:[1],value:[[2, 2]]
场景3: Map
<String[], String[]>
转 Map<Integer[], Long[]>
Map<String[], String[]>
map = toMap(toArray("1"), toArray("2", "8")); Transformer<String[], Integer[]>
keyTransformer = new SimpleClassTransformer<>
(Integer[].class); Transformer<String[], Long[]>
valueTransformer = new SimpleClassTransformer<>
(Long[].class); //key和value转成不同的类型 Map<Integer[], Long[]>
returnMap = toMap(map, keyTransformer, valueTransformer); assertThat(returnMap, allOf(hasEntry(toArray(1), toArray(2L, 8L))));
K
- the key typeV
- the value typeI
- 返回的map ,key的类型J
- 返回的map ,value的类型inputMap
- the input mapkeyTransformer
- key 转换器,如果是null,那么key直接使用inputMap
的keyvalueTransformer
- value 转换器,如果是null,那么value直接使用inputMap
的valueinputMap
是null或者empty,返回 Collections.emptyMap()
keyTransformer
是null,那么key直接使用inputMap
的keyvalueTransformer
是null,那么value 直接使用inputMap
的 valueMapUtils.transformedMap(Map, Transformer, Transformer)
,
TransformedMap
,
issues497public static <V,K,E extends Map.Entry<K,V>> Map<K,V> toMap(Collection<E> mapEntryCollection)
mapEntryCollection
转成map (LinkedHashMap
).
- 返回是的是
LinkedHashMap
,顺序依照参数mapEntryCollection
,key是Map.Entry.getKey()
,value 是Map.Entry.getValue()
Map.Entry
已知实现类,你可以使用Pair
,或者AbstractMap.SimpleEntry
Pair
示例:Map返回:<String, String>
map = toMap(toList(// Pair.of("张飞", "丈八蛇矛"), Pair.of("关羽", "青龙偃月刀"), Pair.of("赵云", "龙胆枪"), Pair.of("刘备", "双股剑"))); LOGGER.debug(JsonUtil.format(map));{ "张飞": "丈八蛇矛", "关羽": "青龙偃月刀", "赵云": "龙胆枪", "刘备": "双股剑" }
AbstractMap.SimpleEntry
示例:Map返回:<String, String>
map = ConvertUtil.toMap( toList( new SimpleEntry<>
("张飞", "丈八蛇矛"), new SimpleEntry<>
("关羽", "青龙偃月刀"), new SimpleEntry<>
("赵云", "龙胆枪"), new SimpleEntry<>
("刘备", "双股剑"))); LOGGER.debug(JsonUtil.format(map));{ "张飞": "丈八蛇矛", "关羽": "青龙偃月刀", "赵云": "龙胆枪", "刘备": "双股剑" }
V
- the value typeK
- the key typeE
- the element typemapEntryCollection
- the map entry collectionmapEntryCollection
是null,返回 Collections.emptyMap()
mapEntryCollection
有元素是null,将会抛出异常 IllegalArgumentException
ArrayUtils.toMap(Object[])
@SafeVarargs public static <V,K> Map<K,V> toMapUseEntrys(Map.Entry<K,V>... mapEntrys)
Map.Entry
数组转成map (LinkedHashMap
).
- 返回是的是
LinkedHashMap
,顺序依照参数Map.Entry
数组顺序,key是Map.Entry.getKey()
,value 是Map.Entry.getValue()
Map.Entry
已知实现类,你可以使用Pair
,或者AbstractMap.SimpleEntry
Pair
示例:Map返回:<String, String>
map = ConvertUtil.toMapUseEntrys( Pair.of("张飞", "丈八蛇矛"), Pair.of("关羽", "青龙偃月刀"), Pair.of("赵云", "龙胆枪"), Pair.of("刘备", "双股剑")); LOGGER.debug(JsonUtil.format(map));{ "张飞": "丈八蛇矛", "关羽": "青龙偃月刀", "赵云": "龙胆枪", "刘备": "双股剑" }
AbstractMap.SimpleEntry
示例:Map返回:<String, String>
map = ConvertUtil.toMapUseEntrys( new SimpleEntry<>
("张飞", "丈八蛇矛"), new SimpleEntry<>
("关羽", "青龙偃月刀"), new SimpleEntry<>
("赵云", "龙胆枪"), new SimpleEntry<>
("刘备", "双股剑")); LOGGER.debug(JsonUtil.format(map));{ "张飞": "丈八蛇矛", "关羽": "青龙偃月刀", "赵云": "龙胆枪", "刘备": "双股剑" }
以前初始化全局map的时候,你可能会这么写
// 除数和单位的map,必须是有顺序的 从大到小. private static final Map现在你可以重构成:<Long, String>
DIVISOR_AND_UNIT_MAP = new LinkedHashMap<>
(); static{ DIVISOR_AND_UNIT_MAP.put(FileUtils.ONE_TB, "TB");//(Terabyte,太字节,或百万兆字节)=1024GB,其中1024=2^10(2的10次方) DIVISOR_AND_UNIT_MAP.put(FileUtils.ONE_GB, "GB");//(Gigabyte,吉字节,又称“千兆”)=1024MB DIVISOR_AND_UNIT_MAP.put(FileUtils.ONE_MB, "MB");//(Megabyte,兆字节,简称“兆”)=1024KB DIVISOR_AND_UNIT_MAP.put(FileUtils.ONE_KB, "KB");//(Kilobyte 千字节)=1024B }// 除数和单位的map,必须是有顺序的 从大到小. private static final Map<Long, String>
DIVISOR_AND_UNIT_MAP = ConvertUtil.toMapUseEntrys( Pair.of(FileUtils.ONE_TB, "TB"), //(Terabyte,太字节,或百万兆字节)=1024GB,其中1024=2^10(2的10次方) Pair.of(FileUtils.ONE_GB, "GB"), //(Gigabyte,吉字节,又称“千兆”)=1024MB Pair.of(FileUtils.ONE_MB, "MB"), //(Megabyte,兆字节,简称“兆”)=1024KB Pair.of(FileUtils.ONE_KB, "KB")); //(Kilobyte 千字节)=1024B代码更加简洁
V
- the value typeK
- the key typemapEntrys
- the entrysentrys
是null,返回 Collections.emptyMap()
entrys
有元素是null,将会抛出异常 IllegalArgumentException
ImmutablePair.ImmutablePair(Object, Object)
,
Pair.of(Object, Object)
public static Properties toProperties(Map<String,String> map)
Properties
.
- 由于 Properties 只能保存非空的key和value,因此如果map 有key或者value是null,将会抛出
NullPointerException
Map返回:<String, String>
map = toMap("name", "feilong"); Properties properties = ConvertUtil.toProperties(map); LOGGER.debug(JsonUtil.format(properties));{"name": "feilong"}
map
- the mapmap
是null,返回 empty PropertiesMapUtils.toProperties(Map)
public static <T> List<T> toList(Enumeration<T> enumeration)
T
- the generic typeenumeration
- the enumerationenumeration
是null,返回 Collections.emptyList()
Collections.list(Enumeration)
Collections.emptyList()
,
Collections.EMPTY_LIST
,
Collections.list(Enumeration)
,
EnumerationUtils.toList(Enumeration)
public static <T> List<T> toList(Collection<T> collection)
collection
转成 list.
- 此方法很适合快速的将set转成list这样的操作
Set返回:<String>
set = new LinkedHashSet<>
(); Collections.addAll(set, "a", "a", "b", "b"); LOGGER.debug("{}", toList(set));[a,b]
T
- the generic typecollection
- the collectioncollection
是null,返回 Collections.emptyList()
collection instanceof List
,那么强转成 list返回new ArrayList(collection)
IterableUtils.toList(Iterable)
,
IteratorUtils.toList(Iterator)
@SafeVarargs public static <T> List<T> toList(T... arrays)
ArrayList
).
- 此方法返回的list可以进行add等操作
- 如果直接使用
Arrays#asList(Object...)
返回的list没有实现Collection#add(Object)
等方法,执行list.add("c")
;操作的话会导致异常!- 而本方法使用
ArrayList.ArrayList(java.util.Collection)
来进行重新封装返回,可以执行正常的list操作
如果你要通过以下方式来构造list:
List此时你可以使用:<String>
list = new ArrayList<>
(); list.add("feilong1"); list.add("feilong2"); list.add("feilong2"); list.add("feilong3");List<String>
list = toList("feilong1", "feilong2", "feilong2", "feilong3");代码会更简洁
有很多时候,参数需要一个对象list,构造的时候,你需要这样
List你可以重构成:<UserAddress>
userAddresseList = new ArrayList<>
(); UserAddress userAddress = new UserAddress(); userAddress.setAddress("上海"); userAddresseList.add(userAddress);UserAddress userAddress = new UserAddress(); userAddress.setAddress("上海"); List<UserAddress>
userAddresseList = toList(userAddress);
T
- the generic typearrays
- T数组arrays
是null或者empty,返回 Collections.emptyList()
assertEquals(emptyList(), toList((User[]) null));
//-------------------------------------------------
List<User>
list = newArrayList();
list.add(null);
assertEquals(list, toList((User) null));
否则返回 new ArrayList<T>(Arrays.asList(arrays));
Arrays.asList(Object...)
,
Collections.singleton(Object)
,
Collections.addAll(Collection, Object...)
,
Collections.singletonList(Object)
,
"org.springframework.util.CollectionUtils#arrayToList(Object)"@SafeVarargs public static <T> Set<T> toSet(T... arrays)
LinkedHashSet
).
- 此方法返回的是
LinkedHashSet
如果你要通过以下方式来构造Set:
Set此时你可以使用:<String>
set = new LinkedHashSet<>
(); set.add("feilong1"); set.add("feilong2"); set.add("feilong2"); set.add("feilong3");Set<String>
set = toSet("feilong1", "feilong2", "feilong2", "feilong3");代码会更简洁
有很多时候,参数需要一个对象Set,构造的时候,你需要这样
Set你可以重构成:<UserAddress>
userAddresseSet = new LinkedHashSet<>
(); UserAddress userAddress = new UserAddress(); userAddress.setAddress("上海"); userAddresseSet.add(userAddress);UserAddress userAddress = new UserAddress(); userAddress.setAddress("上海"); Set<UserAddress>
userAddresseSet = toSet(userAddress);
T
- the generic typearrays
- the arraysarrays
是null或者empty,返回 Collections.emptySet()
assertEquals(emptySet(), toSet((User[]) null));
//-------------------------------------------------
Set<User>
set = new LinkedHashSet<>();
set.add(null);
assertEquals(list, toSet((User) null));
否则返回 new LinkedHashSet<T>(Arrays.asList(arrays));
@SafeVarargs public static <T> T[] toArray(T... arrays)
String[] array = ConvertUtil.toArray("1", "2"); = ["1", "2"]; String[] emptyArray = ConvertUtil.<String>
toArray(); = [] ; //= new String[] {}; Integer[] emptyArray = ConvertUtil.<Integer>
toArray(); = [] ; //= new Integer[] {}; //注意 String[] nullArray = ConvertUtil.toArray(null) = null; ConvertUtil.toArray((String) null) = new String[] { null }
数组是具体化的(reified),而泛型在运行时是被擦除的(erasure)。
泛型擦除的规则:
数组是在运行时才去判断数组元素的类型约束,而泛型正好相反,在运行时,泛型的类型信息是会被擦除的,只有编译的时候才会对类型进行强化。
- 所有参数化容器类都被擦除成非参数化的(raw type); 如 List
<E>
、List<List<E>>
都被擦除成 List- 所有参数化数组都被擦除成非参数化的数组;如 List
<E>
[],被擦除成 List[]- Raw type 的容器类,被擦除成其自身,如 List
<E>
被擦 除成 List- 原生类型(int,String 还有 wrapper 类)都擦除成他们的自身
- 参数类型 E,如果没有上限,则被擦除成 Object
- 所有约束参数如
<? Extends E>
、<X extends E>
都被擦 除成 E- 如果有多个约束,擦除成第一个,如
<T extends Object & E>
,则擦除成 Object这将会导致下面的代码:
public static调用的时候,<K, V>
Map<K, V[]>
toArrayValueMap(Map<K, V>
singleValueMap){ Map<K, V[]>
arrayValueMap = newLinkedHashMap(singleValueMap.size());//保证顺序和参数singleValueMap顺序相同 for (Map.Entry<K, V>
entry : singleValueMap.entrySet()){ arrayValueMap.put(entry.getKey(), toArray(entry.getValue()));//注意此处的Value不要声明成V,否则会变成Object数组 } return arrayValueMap; }Map会出现异常<String, String>
singleValueMap = MapUtil.newLinkedHashMap(2); singleValueMap.put("province", "江苏省"); singleValueMap.put("city", "南通市"); Map<String, String[]>
arrayValueMap = MapUtil.toArrayValueMap(singleValueMap); String[] strings = arrayValueMap.get("province");//此时返回的是 Object[]java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
T
- the generic typearrays
- the arraysarrays
是null,返回nullArrayUtils.toArray(Object...)
public static <T> T[] toArray(Collection<T> collection, Class<T> arrayComponentType)
collection
转成数组.
List以前你需要写成:<String>
list = new ArrayList<>
(); list.add("xinge"); list.add("feilong");list.toArray(new String[list.size()]);现在你只需要写成:String[] array = ConvertUtil.toArray(list, String.class); LOGGER.info(JsonUtil.format(array));返回:["xinge","feilong"]
T
- the generic typecollection
- collectionarrayComponentType
- 数组组件类型的 Classcollection
是null,直接返回nullarrayComponentType
是null,抛出 NullPointerException
Array.newInstance(Class, int)
,
Array.newInstance(Class, int...)
,
Collection.toArray()
,
Collection.toArray(Object[])
,
List.toArray()
,
List.toArray(Object[])
,
Vector.toArray()
,
Vector.toArray(Object[])
,
LinkedList.toArray()
,
LinkedList.toArray(Object[])
,
ArrayList.toArray()
,
ArrayList.toArray(Object[])
,
IteratorUtils.toArray(Iterator,Class)
,
"org.springframework.util.StringUtils#toStringArray(Collection)"public static <T> T[] toArray(String[] toBeConvertedValue, Class<T> targetType)
toBeConvertedValue
转成指定类型 targetType
的数组.
String[] ss = { "2", "1" }; toArray(ss, Long.class); = new Long[] { 2L, 1L } ConvertUtil.toArray((String[]) null, Serializable.class) = null
T
- the generic typetoBeConvertedValue
- the valuestargetType
- 要被转换的目标类型toBeConvertedValue
是null,那么返回nulltargetType
是null,抛出 NullPointerException
ConvertUtils.convert(String[], Class)
ConvertUtils.convert(String[], Class)
,
ConvertUtilsBean.convert(String[], Class)
public static String[] toStrings(Object toBeConvertedValue)
toBeConvertedValue
转成String
数组.
该方法很适合将 非字符串数组的数组 转换成 字符串数组,比如
URL[] urls = { URLUtil.newURL("http://www.exiaoshuo.com/jinyiyexing0/"), URLUtil.newURL("http://www.exiaoshuo.com/jinyiyexing1/"), URLUtil.newURL("http://www.exiaoshuo.com/jinyiyexing2/"), null }; LOGGER.debug(JsonUtil.format(ConvertUtil.toStrings(urls)));返回:[ "http://www.exiaoshuo.com/jinyiyexing0/", "http://www.exiaoshuo.com/jinyiyexing1/", "http://www.exiaoshuo.com/jinyiyexing2/", null ]还有诸如 Integer[] 转成 String[]
ConvertUtil.toStrings(new Integer[] { 1, 2, 5 }) = [ "1", "2", "5" ]也可以将字符串 解析成数组 in the Java language into a
List
individual Strings for each element, 根据以下规则:字符串转成数组的规则:
- The string is expected to be a comma-separated list of values.
- 自动去除开头的 '{' 和 结束的'}'.
- 每个元素前后的空格将会去除.
- Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are valid.
示例:
ConvertUtil.toStrings("{5,4, 8,2;8 9_5@3`a}"); = ["5","4","8","2","8","9","5","3","a"]
toBeConvertedValue
- the to be converted valuetoBeConvertedValue
是null,返回nullArrayConverter.convertToType(Class, Object)
,
ArrayConverter.parseElements(Class, String)
,
convert(Object, Class)
public static <T> Iterator<T> toIterator(Object toBeConvertedValue)
toBeConvertedValue
转成Iterator
类型.
// null toIterator(null) = null //PrimitiveArray int[] i2 = { 1, 2 }; Iterator<Integer>
iterator = toIterator(i2); //逗号分隔的字符串 Iterator<String>
iterator = toIterator("1,2"); //collection List<String>
list = new ArrayList<>
(); list.add("aaaa"); list.add("nnnnn"); Iterator<String>
iterator = toIterator(list); //Enumeration Enumeration<Object>
enumeration = new StringTokenizer("this is a test"); Iterator<String>
iterator = toIterator(enumeration);
- 逗号分隔的字符串,先使用
toStrings(Object)
转成数组- 数组(包括 包装类型数组 以及 原始类型数组)
- 如果是
Map
,将Map.values()
转成Iterator
Collection
Iterator
Enumeration
Dictionary
Node
NodeList
T
- the generic typetoBeConvertedValue
- the to be converted valuetoBeConvertedValue
是null,返回nulltoBeConvertedValue
是字符串,先转成数组,再转成迭代器IteratorUtils.getIterator(Object)
Collection.iterator()
,
EnumerationIterator.EnumerationIterator(Enumeration)
,
IteratorUtils.asIterator(Enumeration)
,
IteratorUtils.getIterator(Object)
,
"org.apache.taglibs.standard.tag.common.core.ForEachSupport#supportedTypeForEachIterator(Object)"public static <T> T convert(Object toBeConvertedValue, Class<T> targetType)
toBeConvertedValue
转成指定 targetType
类型的对象.
ConvertUtil.convert("1", Integer.class) =1 ConvertUtil.convert("", Integer.class) =0 ConvertUtil.convert("1", Long.class) =1
原来的写法:Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); int length = actualTypeArguments.length; Class现在可以重构成:<?>
[] klasses = new Class<?>
[length]; for (int i = 0, j = length; i<
j; ++i){ klasses[i] = (Class<?>
) actualTypeArguments[i]; } return klasses;Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); return convert(actualTypeArguments, Class[].class);
- 如果
targetType
的转换器没有注册,那么传入的value原样返回,
比如ConvertUtil.convert("zh_CN", Locale.class)
由于找不到converter,那么返回"zh_CN".- 如果转换不了,会使用默认值
- 如果传的
toBeConvertedValue
是toBeConvertedValue.getClass().isArray()
或者Collection
- 如果
targetType
不是数组那么会取第一个元素进行转换,
参见AbstractConverter.convert(Class, Object)
,调用的AbstractConverter.convertArray(Object)
方法- 如果
targetType
是数组- 参见
ArrayConverter#convertToType(Class, Object)
会基于targetType 构造一个数组对象,大小长度就是toBeConvertedValue
的大小或者长度, 然后迭代toBeConvertedValue
依次进行转换
该方法不适合 list转换成字符串,比如:
ConvertUtil.toString(toList("张飞", "关羽", "", "赵云"), String.class) = "张飞",请使用
toString(Collection, ToStringConfig)
该方法也不适合 array 转换成字符串,比如:
Integer[] int1 = { 2, null, 1, null }; LOGGER.debug(ConvertUtil.toString(int1),String.class); = 2
参见
ArrayConverter#convertToString(Object)
在转换的过程中,如果发现object是数组,将使用Array#get(Object, int)
来获得数据,
如果发现不是数组,将会将object转成集合ArrayConverter#convertToCollection(Class, Object)
再转成迭代器Collection.iterator()
在将object转成集合
ArrayConverter#convertToCollection(Class, Object)
时候,有以下规则:
- The string is expected to be a comma-separated list of values.
- 字符串可以被'{' and '}'分隔符包裹.
- 去除前后空白.
- Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are valid.
默认:
字段 说明 int defaultSize 指定构建的默认数组的大小 or if less than zero indicates that a null
default value should be used.char delimiter = ',' 分隔符,转成的string中的元素分隔符 char[] allowedChars = new char[] {'.', '-'} 用于 StreamTokenizer
分隔字符串boolean onlyFirstToString = true; 只转第一个值
T
- the generic typetoBeConvertedValue
- 需要被转换的对象/值targetType
- 要转成什么类型targetType
是null,抛出 NullPointerException
toBeConvertedValue
是null,那么直接返回nullConvertUtils.convert(Object, Class)
ConvertUtils.convert(Object, Class)
,
AbstractConverter.convert(Class, Object)
,
ArrayConverter.convertToType(Class, Object)
public static Locale toLocale(Object locale)
locale
- 可以是 null ,字符串 或者 直接的 Locale
对象locale
是null,返回 nulllocale instanceof Locale
,返回 (Locale) locale
locale instanceof String
,返回 LocaleUtils.toLocale(String)
UnsupportedOperationException
LocaleUtils.toLocale(String)
Copyright © 2008-2019 by feilong