commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Baltz, Kenneth" <Kba...@firstam.com>
Subject [Digester]How to populate a Map using Digester 1.4
Date Mon, 03 Feb 2003 22:54:50 GMT
In honor of the new release of Digester and because it's been discussed here
before, I thought I'd post a quick How-To for building Maps using Digester
1.4.

Prior to 1.4, it was difficult to populate a Map with an Object created by a
CreateObject rule because it lived only in the stack and the only direct way
to access it was through a setNext rule.  However, SetNext would not allow
you to call a method with any parameters (other than the object on the top
of the stack).  So the advice for populating a HashMap was to build a proxy
object that would translate addMyObject( MyObject ) into put(
MyObject.getKey(), MyObject ).  

Enter 1.4 and the a new CallParamRule.  The solution to this problem is now
much more straight forward.  You can use any object on the stack as an
argument to any method normally callable via a CallMethodRule.  I was going
to insert my own example here, but the Junit test case used to verify this
behavior works just as well.

For the following XML: 
<?xml version='1.0'?>
<map>
  <key name='The key'/>
  <value name='The value'/>
</map>

Use the following digester to build a HashMap of (key, value) pairs:

// Instantiate the HashMap
digester.addObjectCreate("map", HashMap.class);
// Call HashMap.put( Object, Object ) on the object we created above
digester.addCallMethod("map", "put", 2);
// Create a custom object
digester.addObjectCreate("map/key", AlphaBean.class);
// Set the name parameter of that object
digester.addSetProperties("map/key");
// Indicate that the AlphaBean should be the first argument to put()
digester.addCallParam("map/key", 0, true);
// Create another custom object
digester.addObjectCreate("map/value", BetaBean.class);
// Set the name parameter of that object
digester.addSetProperties("map/value");
// Indicate that the BetaBean should be the second argument to put()
digester.addCallParam("map/value", 1, true);

This will create a map of AlphaBean keys to BetaBean values. 

Hope that helps.

K.C.

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message