大家好,又见面了,我是你们的朋友全栈君。
/**
* @Description //TODO Map工具类
* @Date 2020/5/7 9:54
* @Author huangwb
**/
public class MapUtils {
/**
* @return void
* @Author huangwb
* @Description //TODO 对象转换成map
* @Date 2020/5/7 9:56
* @Param [t 对象,ignoreFields 忽略字段]
**/
public static <T> Map<String, Object> objectToMap(T t, String... ignoreFields) {
Map<String, Object> map = new HashMap<>();
Field[] declaredFields = t.getClass().getDeclaredFields();
List<String> ignoreFieldList = Arrays.asList(ignoreFields);
Arrays.stream(declaredFields).forEach(data -> {
data.setAccessible(true);
try {
if (ignoreFieldList.isEmpty() || !ignoreFieldList.contains(data.getName())) {
map.put(data.getName(), data.get(t));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
return map;
}
public static void main(String[] args) {
TUserInfo tUserInfo = new TUserInfo();
tUserInfo.setId("susisda");
tUserInfo.setUserName("susisda");
tUserInfo.setCreateTime(new Date());
Map<String, Object> map = objectToMap(tUserInfo);
System.out.println(JSON.toJSONString(map));
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/133630.html原文链接:https://javaforall.cn