BeanMap实现Java Bean转Map简单

将一个Java Bean转换为Map数据结构,key为Bean字段名,value为Bean字段值,允许通过map的api进行调用

缺点:不能自定义key名称

pom.xml依赖

1
2
3
4
5
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>

User Bean

1
2
3
4
5
6
7
@Data
public class User {
private String userName;
private String realName;
private String password;
private int age;
}

BeanMap示例

1
2
3
4
5
6
7
8
9
10
11
12
13
public class BeanMapDemo {
public static void main(String[] args) {
User user = new User();
user.setUserName("appblog");
user.setRealName("Joe.Ye");
user.setPassword("123456");
user.setAge(28);
BeanMap userMap = new BeanMap(user);
for (Map.Entry<Object, Object> entry : userMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}

运行结果

1
2
3
4
5
Key: realName, Value: Joe.Ye
Key: password, Value: 123456
Key: userName, Value: appblog
Key: class, Value: class me.yezhou.User
Key: age, Value: 28

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :