将map转成对应对象的三种实现方式一:反射

代码参见:https://gitee.com/WChengHe/springboot

话不多少,直接先贴代码。

1:工具类

思路:工具类将map转成对应对象的方法,入参是map和目标实体类,我们的实体类中是标准的set、get方法,要map转成对应的实体类对象需要map中的字段和我们实体类的属性字段匹配。获取到map中的字段,然后拼装成标准的set方法,利用反射获取到我们目标实体类对象中的这个set方法,并把相应的参数放进去调用。

可能存在的问题:1、需要map中字段和实体类对象的字段匹配,并且实体类中get\set方法要标准;2、利用反射效率会比较低。

package com.wch.SpringBootTestDemo.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

@SuppressWarnings("all")
public class MetaClassUtil {

	/**
	 * 用于将map转成对象
	 * @param map
	 * @param object
	 * @return
	 * @throws Exception 
	 */
	public static Object mapToObject(Map<String, Object> map,Object object){
		
		Field[] fields = object.getClass().getDeclaredFields();
		for(int i=0;i<fields.length;i++){
			String fieldName = fields[i].getName();
			String key = toUpperCaseFirstOne(fieldName);
			String mapValue = (map.get(key)==null?"":map.get(key).toString());
			try {
				object.getClass().getMethod("set"+key,String.class).invoke(object, mapValue);		
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return object;		
	}
	
	
	//首字母转小写
	public static String toLowerCaseFirstOne(String s){
	  if(Character.isLowerCase(s.charAt(0)))
	    return s;
	  else
	    return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
	}


	//首字母转大写
	public static String toUpperCaseFirstOne(String s){
	  if(Character.isUpperCase(s.charAt(0)))
	    return s;
	  else
	    return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
	}
}

2:实体类:注意要序列化

package com.wch.SpringBootTestDemo.entity;

import java.io.Serializable;

import org.springframework.stereotype.Component;

@Component
public class User implements Serializable{


	
	private String username;  //登录名
	private String password;  //密码
	private String name;     //名称
	
	
	
	
	public User() {
		super();
	}
	
	public User(String username) {
		super();
		this.username = username;
	}

	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	

	public User(String username, String password, String name) {
		super();
		this.username = username;
		this.password = password;
		this.name = name;
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", name=" + name + "]";
	}
	
	
	
	
}

3:使用

package com.wch.SpringBootTestDemo.dao.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.wch.SpringBootTestDemo.dao.UserDao;
import com.wch.SpringBootTestDemo.entity.User;
import com.wch.SpringBootTestDemo.util.MetaClassUtil;

@Service
public class UserDaoImpl implements UserDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public User getUserInfoByName(String userName){
		// TODO Auto-generated method stub
		String sql = "SELECT PASSWORD,USERNAME,NAME FROM PM_USER A WHERE USERNAME = ?";
		Map<String, Object> userMap = jdbcTemplate.queryForMap(sql, new Object[]{userName});
		User obj = new User();
		//将查询到的map数据转成user对象
		User user = (User) MetaClassUtil.mapToObject(userMap,obj);
		return user;
	}

}

 

    原文作者:琴瑟和鸣1
    原文地址: https://blog.csdn.net/qq_22596931/article/details/86637540
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞