You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by "Craig R. McClanahan" <Cr...@eng.sun.com> on 2000/12/28 23:03:39 UTC

Re: PropertyUtils handling multiple getter methods

See below.

Chandan Kulkarni wrote:

>   I had a question about this part of PropertyUtils.java.
> ====================================================            public static
> PropertyDescriptor getPropertyDescriptor(Object bean,
>                       String name) <snipped>      PropertyDescriptor
> descriptors[] = getPropertyDescriptors(bean);
>      if (descriptors == null)
>         return (null);
>      for (int i = 0; i < descriptors.length; i++) {
>          if (name.equals(descriptors[i].getName()))
>               return (descriptors[i]);
>      }========================================================The method
> getPropertyDescriptorcalls        getPropertyDescriptors(bean)and iterates
> through them to get a match on the name. Incase the Bean class contains
> ArrayList items; It requires to have 2 getItems methods 1)   ArrayList
> getItems() - to be used when you use the            <logic:iterate
> name="Beanname" property="items" >2)  It also requires an indexed
> getter        Item getItem(int index)    to handle the form input fields
> within the iterate tag. If you find the wrong descriptor first, you get a
> NoSuchMethodExceptionI propose getPropertyDescriptor take another parameter
> (which says whether its an Indexedproperty we are looking for) or create
> anothergetIndexedPropertyDescriptor. I'll probably do that to handle nested,
> indexed properties to get <logic:iterate> to work...       -Chandan.

PropertyUtils is using the standard JavaBeans introspection under the covers, in
order to identify the actual method names of the getters and setters.  In
particular, you are required to use the property naming conventions outlined in
the JavaBeans specification, version 1.0.1.

In your example above, you are using two different property names ("items"
versus "item"), so the introspection code will consider those to be two
different properties.  It is legal to provide both array-based and index-based
getters and setters for the same property, but you must use the same name -- for
example:

    Item[] getItems();
    Item getItems(int index);
    void setItems(Item items[]);
    void setItems(int index, Item item);

If you do this, PropertyUtils uses the following algorithm to retrieve an
indexed property value at a particular subscript:
* If there is an indexed getter (Item getItems(int index)),
  call it directly
* Otherwise, call the array getter (Item[] getItems()) and
  access the requested element out of the array.

Craig McClanahan