Wednesday, March 25, 2015

Spring Reflection + Commons Colletion

import java.lang.reflect.Field;

import org.apache.commons.collections.Transformer;
import org.springframework.util.ReflectionUtils;

 public class TransformerUtils {
  public static Transformer forFieldName(final String fieldName) {
   return new Transformer() {
     @Override 
     public Object transform(Object object) {
     Field f = ReflectionUtils.findField(object.getClass(), fieldName);
     ReflectionUtils.makeAccessible(f);
     return ReflectionUtils.getField(f, object);
    }
   };
  }
 }


example:
Collection zentraleTermine; // test data 
Collection terminIds = CollectionUtils.collect(zentraleTermine,TransformerUtils.forFieldName(ZentralerTerminConst.ID));