Java 反射 Bean 属性 API
是否有任何标准方法来访问 Java Bean 属性,例如
class A {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
,我可以使用 Reflection API 访问此 java bean 属性名称,这样当我更改属性值时,当我设置和获取该属性的值时,会自动调用 getName 和 setName 方法
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;
}
}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我尝试过 BeanUtils 以及 PropertyDescriptors,因为我没有传递给我的方法的类的信息。我什至不知道传递的属性的数据类型,因此设置值变得很困难。我知道 BeanUtils 应该自动为属性进行转换并设置它,但它没有为我保存数据。所以最后我只能靠获取田地了。这就是我所做的:
我做了一个类似的 switch-case 将所有属性类型转换为正确的类型。从页面获取时,request.getParameter(paramname) 始终返回 String,因此这种转换对我有用。任何更好的直接数据转换选项都会非常有帮助。
I have tried BeanUtils as well as PropertyDescriptors because I did not have the information on the class that was passed to my method. I did not even know the data types of the properties passed and so setting values became difficult. I know that BeanUtils should do the conversion automatically for the property and set it but it was not saving the data for me. So finally, I had to rely on getting the fields. Here is what I did:
I did a similar switch-case to convert all property types to correct types. When fetching from the page, request.getParameter(paramname) was always returning String so this conversion worked for me. Any better options for direct data conversion will be really helpful.
使用
java.beans.PropertyDescriptor
在您的情况下:
Use a
java.beans.PropertyDescriptor
In your case:
你需要的是 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)Example code:
你的问题很不清楚,但如果我明白了:
是的。
java.beans
包具有所谓的内省器
。在那里您可以读取 bean 的属性。您可以通过名称找到所需的
PropertyDescriptor
,然后可以调用getReadMethod().invoke(..)
You question is very unclear, but if I get it:
Yes. The
java.beans
package has the so calledIntrospector
. There you can read the properties of a bean.You can find the desired
PropertyDescriptor
by its name and you can callgetReadMethod().invoke(..)