开发者社区> 问答> 正文

JAVA里 获取Bean对象属性的代码怎样编写?

已解决

JAVA里 获取Bean对象属性的代码怎样编写?

展开
收起
gxx1 2022-04-01 12:37:05 423 0
1 条回答
写回答
取消 提交回答
  • 推荐回答

    通过查询相关代码如下:

    public void test(Project project){undefined

    BeanInfo beanInfo;

    try{undefined

    //throws IntrospectionException

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

    if(beanInfo!=null){undefined

    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

    for(PropertyDescriptor p:propertyDescriptors){undefined

    //获得属性名称

    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){undefined

    }catch (InvocationTargetException e1){undefined

    }catch (IllegalAccessException e2){undefined

    }

    上述代码就鞥够解决获取bean属性的问题,我们可以根据其进行应用了。

    2022-04-01 12:40:51
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载