008-TreeMap、Map和Bean互转、BeanUtils.copyProperties(A,B)拷贝、URL编码解码、字符串补齐

时间:2018-03-22 17:06:58   收藏:0   阅读:1158

1、TreeMap 有序Map

  无序有序转换

  使用默认构造方法:

public TreeMap(Map<? extends K, ? extends V> m)

2、Map和Bean互转

BeanUtils位于org.apache.commons.beanutils.BeanUtils下面,其方法populate的作用解释如下:
完整方法:
BeanUtils.populate( Object bean, Map properties ),

这个方法会遍历map<key, value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。

2.1、bean 转换成 map

Person person1=new Person();  
person1.setName("name1");  
person1.setSex("sex1");  
Map<String, String> map = BeanUtils.describe(person1);  

2.2、map 转换成 bean

public static <T> T map2Bean(Map<String, String> map, Class<T> class1) {  
  T bean = null;  
  try {  
    bean = class1.newInstance();  
    BeanUtils.populate(bean, map);  
  } catch (Exception e) {  
    e.printStackTrace();  
  }  
  return bean;  
}  

3、BeanUtils.copyProperties(A,B)拷贝

  3.1、package org.springframework.beans;中的

    BeanUtils.copyProperties(A,B);//A→B 是A中的值付给B

  3.2、package org.apache.commons.beanutils;(常用)

    BeanUtils.copyProperties(A,B);//B→A 是B中的值付给A

  3.3、package org.apache.commons.beanutils;(常用)

    PropertyUtils.copyProperties(A,B);//B→A 是B中的值付给A

  注意:PropertyUtils提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,而BeanUtils不支持这个功能,但是速度会更快一些.

4、URL编码解码

  编码:java.net.URLEncoder.encode(String s)

  解码:java.net.URLDecoder.decode(String s);    

5、字符串补齐

  org.apache.commons.lang.StringUtils  

String test ="123456";
String value = StringUtils.leftPad(test, 10, "0");
System.out.println(value);

  输出:0000123456

 

原文:https://www.cnblogs.com/bjlhx/p/8624284.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!