javabean实体类对象转为Map类型对象的方法

在项目中需要用到对象转Map的需求,就记录下来。防止以后需要用到的。

 public static Map<String, Object> beanToMap(Object obj) { 
         Map<String, Object> params = new HashMap<String, Object>(0); 
         try { 
             PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
             PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
             for (int i = 0; i < descriptors.length; i++) { 
                 String name = descriptors[i].getName(); 
                 if (!"class".equals(name)) { 
                     params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
                 } 
             } 
         } catch (Exception e) { 
             e.printStackTrace(); 
         } 
         return params; 
 }

需要的jar包 maven项目上

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>


		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.2</version>
		</dependency>


获取上面两个jar的网址分别是:http://commons.apache.org/beanutils/  

http://commons.apache.org/proper/commons-logging/

猜你喜欢

转载自blog.csdn.net/papima/article/details/78484514
今日推荐