Java Reflection Beans Property API

狂风中的少年 提交于 2019-11-27 02:07:47

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:

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"); 

You question is very unclear, but if I get it:

Yes. The java.beans package has the so called Introspector. There you can read the properties of a bean.

BeanInfo info = Introspector.getBeanInfo(Bean.class);
PropertyDescriptor[] pds = info.getPropertyDescriptors();

You can find the desired PropertyDescriptor by its name and you can call getReadMethod().invoke(..)

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:

Field[] fields = className.getDeclaredFields();
for (int i=0; i<fields.length ;i++)
{
  String element = fields[i].getName();
  String propertyType = fields[i].getType().getName();
  fields[i].setAccessible(true);
  if(propertyType.equalsIgnoreCase("java.lang.Integer"))
    {
      fields[i].set(mypojoObj, Integer.parseInt(parameterValue));
    }
    else
    {
      fields[i].set(mypojoObj, parameterValue);
    }
 }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!