Sunday, January 18, 2009

Transformer Invoker: For a collection of beans, collect a property

How many times have you had to collect a property from a list of beans, statically or dynamically? I use this little method a lot. For-loops are nice, but because this uses reflection to get the value, you can cook up a factory to get the data.

The code:

package com;
import java.util.*;
import org.apache.commons.collections.*;
public class TransformerExample
{
public static void main(String[] args)
{
List list = Arrays.asList(new DTO("Bob"), new DTO("Larry"), new DTO("Mo"), new DTO("Joe"));
Collection<String> names = CollectionUtils.collect(list, TransformerUtils.invokerTransformer("getName"));
for (String name : names)
{
System.out.println("name = " + name);
}
}
public static class DTO
{
private String name;
public DTO(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
}



The results:

name = Bob
name = Larry
name = Mo
name = Joe
Author: Philip A Senger

3 comments:

  1. Hello,

    Thanks for this post , it is really what I need to boost my application.
    Just a question did you tried the generics commons collections provided by http://larvalabs.com/collections/download.html.
    I want to use it but I am sure it is a nobug version...

    ReplyDelete
  2. This is awesome ..... I just found about the commons collections and have no words to describe the range of functionality provided in it ... Thanks a lot for posting all this info

    ReplyDelete
  3. One question about the invoker transformer .. Hardcoding the getter as in TransformerUtils.invokerTransformer("getName")); does create a problem .. what if the DTO model is changes to say fullName.

    For a Big System the effect of this change can be pretty intense. What do you say ?

    ReplyDelete