Java 反射 Bean 属性 API [英] 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;
}
}
那么我可以使用反射 API 访问这个 java bean 属性名称,以便当我更改属性的值时,在设置和获取该属性的值时会自动调用 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 的回答).但是,直接使用它是非常糟糕的,因此您可以使用提供基于属性的访问的库之一.最著名的可能是 Apache Commons/BeanUtils(另一个是 Spring 的 BeanWrapper
抽象)
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 反射 Bean 属性 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!