当前位置:网站首页>map和实体类互转的代码示例
map和实体类互转的代码示例
2022-06-21 16:04:00 【AinUser】
# 1. 实体转Map
public class Test {
public static void main(String[] args) {
long s1 = System.currentTimeMillis();
Map<String, Object> dataMap = objectToMap(new User().setUser());
long s2 = System.currentTimeMillis();
System.out.println("花费时间毫秒:"+(s2-s1));
System.out.println(dataMap);
}
public static Map<String, Object> objectToMap(Object object){
Map<String,Object> dataMap = new HashMap<>();
Class<?> clazz = object.getClass();
for (Field field : clazz.getDeclaredFields()) {
try {
field.setAccessible(true);
dataMap.put(field.getName(),field.get(object));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return dataMap;
}
}
# 2. Map转实体
public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
if (null == map){
return null;
}
T t = null;
try {
t = entity.newInstance();
for(Field field : entity.getDeclaredFields()) {
if (map.containsKey(field.getName())) {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object object = map.get(field.getName());
if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
field.set(t, object);
}
field.setAccessible(flag);
}
}
return t;
} catch (InstantiationException e) {
logger.error("convert error ", e);
} catch (IllegalAccessException e) {
logger.error("convert error ", e);
}
return t;
}边栏推荐
- 垃圾回收器
- Pytest框架
- Design and implementation of face verification system for floating population management
- 今年的 618 不行了?
- Set up your own website (11)
- 从北京“润”到芝加哥,工程师宝玉“滋润”成长的秘诀
- Many software companies are actually "jokes"
- Common formula of derivative__ Common formulas of indefinite integral
- variable
- Calculation of carbon emissions
猜你喜欢
随机推荐
使用 Guzzle 中间件进行优雅的请求重试
Elegant request retry using guzzle Middleware
Common formula of derivative__ Common formulas of indefinite integral
3M互助智能合约系统开发搭建技术
Pytest framework implements pre post processing
栈的生长方向和内存生长方向
[SQLite] solve unrecognized token:“‘“
Simple ideas and procedures for quick sorting
PowerPoint 教程,如何在 PowerPoint 中更改页面方向、幻灯片大小?
Exness: the impact of inflation in the United States is too great, and the leaders of the Federal Reserve have expressed their position one after another
很多软件公司,其实都是“笑话”
疫情数据对应的大陆和全球的矢量数据下载,基于geojson转shp
三色标记清除法
qtcreator报错解决
模板:P6114 【模板】Lyndon 分解&Runs(字符串)
【349期】面试官:如何优雅的自定义 ThreadPoolExecutor 线程池?
QT knowledge: using the qgraphicspixmapitem class
[Error] ‘vector‘ was not declared in this scope
Postman basic operations
Résolution des erreurs signalées par qtcreator








