java 类转map
时间: 2023-11-17 22:49:17 浏览: 41
在Java中,可以通过以下方式将类转换为Map:
1. 使用反射方式实现:
```java
public static Map<String, Object> convertClassToMap(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = object.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
```
2. 使用BeanUtils类库实现(需要导入Apache Commons BeanUtils库):
```java
public static Map<String, Object> convertClassToMap(Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, Object> map = new HashMap<>();
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] propertyDescriptors = propertyUtilsBean.getPropertyDescriptors(object);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
if (!propertyName.equals("class")) {
Object value = propertyUtilsBean.getNestedProperty(object, propertyName);
map.put(propertyName, value);
}
}
return map;
}
```
请注意,上述方法中的`object`参数是需要转换的类的实例对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)