All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.minsin.core.tools.MapUtil Maven / Gradle / Ivy

Go to download

mutils-core 作为mutils组件中的核心模块。 可以被maven项目单独引用,引入后可提供多种帮助类,如StringUtil、NumberUtil、DateUtil等等 maven仓库:https://mvnrepository.com/artifact/cn.minsin/mutils-core

There is a newer version: 0.3.7
Show newest version
package cn.minsin.core.tools;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

/**
 * 此方法提供一些map的常用操作, 更多的可以查询 {@link org.apache.commons.collections4.MapUtils}
 * 
 * @author minsin
 *
 */
public class MapUtil {

	/**
	 * 将一个对象中不为空 、不是static、Private的字段和值取出来生成一个map
	 * 
	 * @param model
	 * @return
	 */
	public static  Map toMap(T model) {
		HashMap hashMap = new HashMap<>();
		Field[] fields = model.getClass().getDeclaredFields();
		for (Field field : fields) {
			int modifiers = field.getModifiers();
			if (Modifier.isStatic(modifiers) || !Modifier.isPrivate(modifiers)||Modifier.isFinal(modifiers)) {
				continue;
			}
			try {
				String key = field.getName();
				field.setAccessible(true);
				Object object = field.get(model);
				if (!StringUtil.isBlank(object)) {
					hashMap.put(key, object);
				}
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return hashMap;
	}

	public static  T mapToObject(Map map, Class clazz) {
		String jsonString = JSON.toJSONString(map);
		return JSON.parseObject(jsonString, clazz);
	}

	/**
	 * 初始化hashmap并且将参数放入map
	 * 
	 * @param k
	 * @param v
	 * @return
	 */
	public static  Map newInstance(Class k, Class v) {
		return new HashMap<>();
	}

	/**
	 * 初始化hashmap并且将参数放入map
	 * 
	 * @param k
	 * @param v
	 * @return
	 */
	public static  Map newInstanceAndPut(K k, V v) {
		Map map = new HashMap();
		map.put(k, v);
		return map;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy