You can try this method. It takes a collection, a method (from the reflection api) and a target class. It invokes the method on all members of the collection and returns a List of the results.
public <T> Collection<T> select(Collection<? extends Object> input, Method getter, Class<T> targetClazz) {
ArrayList<T> result = new ArrayList<T>();
for (Object object : input) {
try {
Object resultObject = getter.invoke(object, (Object[]) null);
if (targetClazz.isAssignableFrom(resultObject.getClass())) {
result.add(targetClazz.cast(resultObject));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return result;
}
I ignored proper error handling for now. Usage:
try {
Method getId = Thing.class.getMethod("getId", null);
Collection<Long> result = select(things, getId, Long.class);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}