java 获取bean的值_JAVA 获取Bean对象的属性名和该属性对应的值

主要使用到了java.beans包下的类,利用底层反射来获取对象对应的属性和方法;

** BeanInfo **:提供有关Bean的显式信息的接口,其中包含类的属性,方法、事件等显式信息,可以通过Introspector底层反射机制获取

** Introspector **:用于构建一个一个全面描述目标bean的BeanInfo对象,使用低层次的反射来研究类的方法,并应用标准设计模式来标识属性存储器、事件源或公共方法。然后深入分析类的超类,并从它那里添加信息

** PropertyDescriptor ** :描述 Java Bean 通过一对存储器方法导出的一个属性以及该属性的getter和setter方法

相关实现代码:

public void test(Project project){

BeanInfo beanInfo;

try{

//throws IntrospectionException

beanInfo=Introspector.getBeanInfo(project.getClass(), Object.class);

if(beanInfo!=null){

PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for(PropertyDescriptor p:propertyDescriptors){

//获得属性名称

System.err.println(p.getName());

//调用该属性名称对应的getter方法

//throws IntrospectionException,InvocationTargetException,IllegalAccessException

Object obj = new PropertyDescriptor(p.getName(), Project.class).getReadMethod().invoke(project);

//调用该属性名称对应的setter方法

//throws IntrospectionException,InvocationTargetException,IllegalAccessException

new PropertyDescriptor(p.getName(), Project.class).getWriteMethod().invoke(project,new Object[]{"1"});

}

}

}catch (IntrospectionException e){

}catch (InvocationTargetException e1){

}catch (IllegalAccessException e2){

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Hutool 工具包中的 `BeanUtil` 类来将一个 List 转换为一个 Map。 示例代码如下: ```java import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import java.util.List; import java.util.Map; public class Test { public static void main(String[] args) { // 假设有一个类 User,有属性 id、name、age List<User> userList = CollUtil.newArrayList( new User(1L, "张三", 20), new User(2L, "李四", 21), new User(3L, "王五", 22) ); // 将 List 转为 Map,以 id 为 key,User 对象为 value Map<Long, User> userMap = CollUtil.toMap(userList, user -> user.getId(), user -> user); // 打印转换后的 Map System.out.println(userMap); } static class User { private Long id; private String name; private Integer age; public User(Long id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } } } ``` 在上面的示例代码中,我们使用 `CollUtil.toMap()` 方法将 List 转为 Map,其中第一个参数是要转换的 List,第二个参数是 key 的获取方式,第三个参数是 value 的获取方式。在本例中,我们将 id 作为 key,User 对象作为 value。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值