I wrote this utility function:
public static <T> List<T> pluck(String fieldName, List list) throws NoSuchFieldException, IllegalAccessException { if (list.isEmpty()) { return new ArrayList<T>(); } Class c = list.get(0).getClass(); Field f = c.getField(fieldName); ArrayList<T> result = Lists.newArrayList(); for (Object object : list) { result.add((T) f.get(object)); } return result; }
I copied this idea from underscore.js . Use case:
ArrayList<Person> people = new ArrayList<Person>; people.add(new Person("Alice", "Applebee")); people.add(new Person("Bob", "Bedmington")); people.add(new Person("Charlie", "Chang")); List<String> firstNames = pluck("firstName", people);
My problem is that if the caller is mistaken, an exception is not thrown until the caller tries to get the object from the list. Ideally, I would like to throw a ClassCastException from the pluck method pluck . However, I see no way to access the list type at runtime.
Is there any trick I can use to make sure the caller does not have an invalid list?
Edit: Thus, using the feedback received, the safe implementation will be as follows:
public static <T,F> List<F> pluck(String fieldName, Class<F> fieldType, List<T> list, Class<T> listType) throws NoSuchFieldException, IllegalAccessException { Field f = listType.getField(fieldName); ArrayList<F> result = new ArrayList<F>(); for (T element : list) { result.add(fieldType.cast(f.get(element))); } return result; }
But actually lambdai seems to be doing what I wanted, so I think I will use this. Thank you Mike!
Disclaimer: LambdaJ ( @GoogleCode | @GitHub ). This project is no longer supported since the release of JDK8 ( JSR 335 , JEP 126 ).