本文介绍了Java Reflection Beans Property API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何标准方法可以访问Java Bean属性,如

Is there any standard way to access Java Bean Property like

class A {
   private String name;

   public void setName(String name){
       this.name = name;
   }

   public String getName(){
       return this.name;
   }

}

所以我可以访问这个java bean使用Reflection API的属性名称,这样当我更改property的值时,当我设置并获取该属性的值时,会自动调用getName和setName的方法

So can I access this java bean property name using Reflection API so that when I change the value of property the methods of getName and setName are called automatically when I set and get values of that property

推荐答案

你需要的是BeanInfo / Introspector机制(参见Bozho的回答)。但是,直接使用它是如此,因此您可以使用其中一个提供基于属性的访问的库。最着名的可能是(另一个是Spring的抽象)

What you need is the BeanInfo / Introspector mechanism (see Bozho's answer). However, it's hell to use this directly, so you can use one of the Libraries that offer property-based access. The best-known is probably Apache Commons / BeanUtils (another one is Spring's BeanWrapper abstraction)

示例代码:

A someBean = new A();

// access properties as Map
Map<String, Object> properties = BeanUtils.describe(someBean);
properties.set("name","Fred");
BeanUtils.populate(someBean, properties);

// access individual properties
String oldname = BeanUtils.getProperty(someBean,"name");
BeanUtils.setProperty(someBean,"name","Barny"); 

这篇关于Java Reflection Beans Property API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:13