Java Bean與Map轉(zhuǎn)換的幾種方式
更新時(shí)間:2025年10月09日 10:17:01 作者:拂曉銀礫
Java Bean與Map轉(zhuǎn)換的幾種方式,包括反射,內(nèi)省,cglib,huTool,cglib動態(tài)代理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
pom文件
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>cglib</groupId>-->
<!-- <artifactId>cglib</artifactId>-->
<!-- <version>3.3.0</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.15</version>
</dependency>
</dependencies>
java代碼
package com.example.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* description:
* Bean 和 Map相互轉(zhuǎn)換
*
* @author DawnStar
* date: 2023/5/31
*/
public class BeanMapTransform {
public static void main(String[] args) {
AnimeBean animeBean = new AnimeBean();
animeBean.setRoleName("加藤惠");
animeBean.setAge(18);
Map<String, Object> properties = new HashMap<>(2);
properties.put("roleName", "加藤惠");
properties.put("age", 18);
System.out.println("-----------------------反射----------------------------------");
reflectMapToBean(AnimeBean.class, properties);
System.out.println("-----------------------內(nèi)省----------------------------------");
introspectToBean(AnimeBean.class, properties);
System.out.println("----------------------huTool----------------------------------");
huToolMapToBean(AnimeBean.class, properties);
System.out.println("----------------------BeanUtils----------------------------------");
beanUtilsMapToBean(AnimeBean.class, properties);
System.out.println("----------------------CGlib----------------------------------");
// 動態(tài)添加字段
properties.put("animeName", "路人女主的養(yǎng)成方法");
// 沒有使用 BeanGenerator
cglibMapToBean(AnimeBean.class, properties);
System.out.println("----------------------動態(tài)添加字段屬性----------------------------------");
Map<String, Object> properties1 = new HashMap<>(2);
// 動態(tài)添加字段
properties.put("animeName", "路人女主的養(yǎng)成方法");
cglibDynamicMapToBean(animeBean, properties1);
}
/**
* 通過反射生成一個map
*/
private static void reflectBeanToMap(Object sourceObject) {
Map<String, Object> map = new HashMap<>();
try {
for (Field declaredField : sourceObject.getClass().getDeclaredFields()) {
// 私有屬性可訪問
declaredField.setAccessible(true);
Object o = declaredField.get(sourceObject);
String name = declaredField.getName();
map.put(name, o);
}
printMap(map);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 通過反射生成一個bean
*
* @param clazz 指定類
* @param propertiesMap 屬性值
*/
private static void reflectMapToBean(Class<?> clazz, Map<String, Object> propertiesMap) {
try {
Object targetObject = clazz.newInstance();
for (Field declaredField : clazz.getDeclaredFields()) {
// 私有屬性可訪問
declaredField.setAccessible(true);
declaredField.set(targetObject, propertiesMap.get(declaredField.getName()));
}
reflectBeanToMap(targetObject);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* 通過自省的方式 beanToMap
*
* @param sourceObject 源對象
*/
private static void introspectToMap(Object sourceObject) {
try {
// 減少一個class屬性
BeanInfo beanInfo = Introspector.getBeanInfo(sourceObject.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Map<String, Object> map = new HashMap<>(propertyDescriptors.length);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String name = propertyDescriptor.getName();
Method readMethod = propertyDescriptor.getReadMethod();
Object invoke = readMethod.invoke(sourceObject);
map.put(name, invoke);
}
printMap(map);
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* Map 轉(zhuǎn) bean
*
* @param clazz 傳入的類型
* @param propertiesMap 屬性map
*/
private static void introspectToBean(Class<?> clazz, Map<String, Object> propertiesMap) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
Object sourceObject = clazz.newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(sourceObject, propertiesMap.get(propertyDescriptor.getName()));
}
introspectToMap(sourceObject);
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException |
InstantiationException e) {
throw new RuntimeException(e);
}
}
private static void huToolBeanToMap(Object sourceObject) {
Map<String, Object> map = BeanUtil.beanToMap(sourceObject, false, false);
printMap(map);
}
private static void huToolMapToBean(Class<?> clazz, Map<String, Object> propertiesMap) {
Object bean = BeanUtil.mapToBean(propertiesMap, clazz, false, CopyOptions.create());
huToolBeanToMap(bean);
}
private static void beanUtilsBeanToMap(Object sourceObject) {
Map<String, Object> map = new HashMap<>();
try {
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(sourceObject.getClass());
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if ("class".equals(propertyDescriptor.getName())) {
continue;
}
String name = propertyDescriptor.getName();
Method readMethod = propertyDescriptor.getReadMethod();
Object invoke = readMethod.invoke(sourceObject);
map.put(name, invoke);
}
printMap(map);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static void beanUtilsMapToBean(Class<?> clazz, Map<String, Object> propertiesMap) {
try {
Object newInstance = clazz.newInstance();
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if ("class".equals(propertyDescriptor.getName())) {
continue;
}
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(newInstance, propertiesMap.get(propertyDescriptor.getName()));
}
cglibBeanToMap(newInstance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void cglibMapToBean(Class<?> clazz, Map<String, Object> propertiesMap) {
try {
Object instance = clazz.newInstance();
BeanMap beanMap = BeanMap.create(instance);
beanMap.putAll(propertiesMap);
Object bean = beanMap.getBean();
System.out.println(bean);
reflectBeanToMap(bean);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static void cglibBeanToMap(Object sourceObject) {
BeanMap beanMap = BeanMap.create(sourceObject);
printMap(beanMap);
}
/**
* 動態(tài)給實(shí)體類添加字段
*
* @param sourceObject 類型
* @param propertiesMap 屬性映射
*/
private static void cglibDynamicMapToBean(Object sourceObject, Map<String, Object> propertiesMap) {
Map<String, Class<?>> propertyMap = new HashMap<>();
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(sourceObject.getClass());
try {
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (!"class".equalsIgnoreCase(propertyDescriptor.getName())) {
propertyMap.put(propertyDescriptor.getName(), propertyDescriptor.getPropertyType());
String name = propertyDescriptor.getName();
Method readMethod = propertyDescriptor.getReadMethod();
Object invoke = readMethod.invoke(sourceObject);
propertiesMap.put(name, invoke);
}
}
DynamicBean dynamicBean = new DynamicBean(sourceObject.getClass(), propertyMap);
dynamicBean.setProperties(propertiesMap);
Object targetObject = dynamicBean.getTargetObject();
Field[] declaredFields = targetObject.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
System.out.println(declaredField.getName());
Object o1 = declaredField.get(targetObject);
System.out.println(o1);
}
System.out.println(targetObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printMap(Map<String, Object> map) {
map.forEach((k, v) -> System.out.println(k + ": " + v));
}
static class DynamicBean {
private Object targetObject;
private BeanMap beanMap;
public DynamicBean(Class<?> clazz, Map<String, Class<?>> propertyMap) {
this.targetObject = generateBean(clazz, propertyMap);
this.beanMap = BeanMap.create(targetObject);
}
public Object getTargetObject() {
return targetObject;
}
/**
* bean 添加屬性和值
*
* @param key 屬性
* @param value 對應(yīng)鍵的值
*/
public void setValue(String key, Object value) {
beanMap.put(key, value);
}
/**
* 獲取屬性值
*
* @param property 屬性
* @return 獲取屬性的值
*/
public Object getValue(String property) {
return beanMap.get(property);
}
public void setProperties(Map<String, Object> propertyMap) {
beanMap.putAll(propertyMap);
}
private Object generateBean(Class<?> superclass, Map<String, Class<?>> propertyMap) {
BeanGenerator generator = new BeanGenerator();
if (null != superclass) {
generator.setSuperclass(superclass);
}
BeanGenerator.addProperties(generator, propertyMap);
return generator.create();
}
}
static class AnimeBean {
private String roleName;
private Integer age;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
}
到此這篇關(guān)于Java Bean與Map轉(zhuǎn)換的幾種方式的文章就介紹到這了,更多相關(guān)Java Bean與Map轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot深入分析運(yùn)行原理與功能實(shí)現(xiàn)
我們發(fā)現(xiàn)springBoot程序開發(fā)比spring程序編寫起來容易的多。配置簡潔,依賴關(guān)系簡單,啟動運(yùn)行容易。那么結(jié)下了我們我們就要思考一下入門程序中的這些功能是怎么實(shí)現(xiàn)的2022-09-09
Java?HashSet的Removals()方法注意事項(xiàng)
這篇文章主要介紹了Java?HashSet的Removals()方法注意事項(xiàng),文章圍繞制主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06
Spring Boot Thymeleaf實(shí)現(xiàn)國際化的方法詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot Thymeleaf實(shí)現(xiàn)國際化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Spring實(shí)戰(zhàn)之調(diào)用實(shí)例工廠方法創(chuàng)建Bean操作示例
這篇文章主要介紹了Spring實(shí)戰(zhàn)之調(diào)用實(shí)例工廠方法創(chuàng)建Bean操作,結(jié)合實(shí)例形式分析了實(shí)例工廠方法創(chuàng)建Bean相關(guān)配置、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2019-11-11

