commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Simon Kitching <si...@ecnetwork.co.nz>
Subject Re: Digester: dynamic property setter
Date Tue, 20 Jul 2004 09:12:47 GMT
On Tue, 2004-07-20 at 20:43, petra staub wrote:

> How can I implement a dynamic property setter?
> 
> I have for instance a bean 'address' with different properties and
> getter/setters...something like:
> 
> public class Address {
>   private String firstname;
>   private String lastname;
>   ...
>   ...
> 
>   public void setFirstname(String str) {
>     firstname = str;
>   }
>   public String getFirstname() {
>     return firstname;
>   }
>   ...
>   ...
> }
> 
> I want now to parse a XML file where the bean properties are
> specified by a 'property tag':
> 
> <address>
>   <property id="firstname">petra</property>
>   <property id="lastname">staub</property>
> </address>
> 
Hi Petra,

If you can write your xml as:
  <address>
    <property id="firstname" value="petra"/>
    <property id="lastname" value="staub"/>
  </address>
then you can use the SetPropertyRule.

If you can write your xml as:
  <address>
    <firstname>petra</firstname>
    <lastname>staub</lastname>
  </address>
then you can either use BeanPropertySetterRule + the ExtendedBaseRules
matcher, or can use the new SetNestedPropertiesRule from the CVS version
of Digester.

But unfortunately I don't know of a way of parsing the xml you indicate
using the standard rules.

You could of course write a custom Rule to do this (or modify the
existing SetPropertyRule to add this feature). If you do so, please
consider submitting it for inclusion in the Digester core. I'm not
currently sure what the best way of doing this is, because it requires
info from both the begin() method (attribute) and body() method
(content), and rules should never store "state" on themselves. Perhaps
an argument could be made that this is ok for this rule, because it
always deals with "leaf" xml elements.

Or, as you say, you could add a setProperty(name, value) method to your
bean that either has a hard-wired if/then structure to call the correct
setter method, or uses reflection upon itself to invoke the appropriate
method, or make the class a DynaBean.

Regards,

Simon


---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Mime
View raw message