一、在Java中,可以通過以下方法將實(shí)體類轉(zhuǎn)換為Map:
- 利用Java反射機(jī)制:
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
- 利用Java 8 Stream API:
public static Map<String, Object> objectToMap(Object obj) {
return Arrays.stream(obj.getClass().getDeclaredFields())
.peek(field -> field.setAccessible(true))
.collect(Collectors.toMap(Field::getName, field -> {
try {
return field.get(obj);
} catch (IllegalAccessException e) {
return null;
}
}));
}
以上兩種方法都可以將實(shí)體類轉(zhuǎn)換為Map。需要注意的是,這些方法僅會(huì)將實(shí)體類中的屬性轉(zhuǎn)換為Map中的鍵值對(duì),不會(huì)包含方法、構(gòu)造器、父類屬性等其他部分。
二、要將map轉(zhuǎn)換為實(shí)體類對(duì)象,可以使用以下方法:
- 使用Java反射機(jī)制:
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class MapToEntity {
public static void main(String[] args) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
map.put("name", "張三");
map.put("age", 25);
User user = mapToEntity(map, User.class);
System.out.println(user);
}
public static <T> T mapToEntity(Map<String, Object> map, Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Field field = clazz.getDeclaredField(key);
field.setAccessible(true);
field.set(obj, value);
}
} catch (InstantiationException | IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
return obj;
}
}
class User {
private String name;
private int age;
// 省略getter和setter方法
}
- 使用第三方庫(kù):例如Jackson、Gson等。這里以Jackson為例:
首先,添加Jackson依賴到項(xiàng)目中(以Maven為例):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
然后,創(chuàng)建實(shí)體類User:文章來源:http://www.zghlxwxcb.cn/news/detail-753303.html
public class User {
private String name;
private int age;
// 省略getter和setter方法
}
接下來,使用Jackson將map轉(zhuǎn)換為User對(duì)象:文章來源地址http://www.zghlxwxcb.cn/news/detail-753303.html
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class MapToEntity {
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "張三");
map.put("age", 25);
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.convertValue(map, User.class);
System.out.println(user);
}
}
到了這里,關(guān)于Java中實(shí)體與Map的相互轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!