Wednesday, June 10, 2009

Using commons bean library to get all properties of a bean

    public String[] getFieldValues( DataObject bean )

    {

        List<String> fieldValues = new ArrayList<String>();

        try

        {

            // TBD: handle null key

            fieldValues.add(PropertyUtils

                .getSimpleProperty(bean, "key")

                .toString());

 

            PropertyDescriptor[] properties =

                PropertyUtils.getPropertyDescriptors(bean);

            for (PropertyDescriptor property : properties)

            {

                String propertyName = property.getName();

                Object propertyValue =

                    PropertyUtils.getSimpleProperty(bean, propertyName);

                if (null != propertyValue

                    && !propertyValue.toString().isEmpty())

                {

                    fieldValues.add(propertyValue.toString());

                }

            }

        }

        catch (Exception ite)

        {

            // TBD: handle this

        }

        return fieldValues.toArray(new String[0]);

    }

 

No comments: