18.11.2009
Iterate over a JFace selection in a for each loop
Just a tiny JFace helper for today: I added SelectionUtils to rcputils. You can use this to iterate over an ISelection using a for each loop:
ISelection selection = someViewer.getSelection();
for (SomeObject obj : SelectionUtils.getIterable(selection, SomeObject.class)) {
// ...
}


Good one.
You could also use the Visitor pattern and save the allocation of the ArrayList.
SelectionUtils.visit(selection, new Visitor<MyObject>(MyObject.class) { void visit(MyObject item) {} });
Also instead of checking for assignable, one could use the AdapterManager to adapt objects in the selection.
SelectionUtils.visit(selection, new AdapterVisitor<IWorkbenchAdapter>(IWorkbenchAdapter.class) {
void visit(IWorkbenchAdapter wba) {
}
);
abstract class AdapterVisitor<E> implements Visitor<Object> {
final IAdapterManager am = Platform.getAdapterManager();
final Class<?> clazz;
public AdapterVisitor(Class<?> clazz) {
this.clazz = clazz;
}
void visit(Object item) {
E adapter = am.getAdapter(item, clazz);
if (adapter != null) visit(adapter);
}
abstract void visit(E item);
}
Also the Visitors method could return a type and the loop would only iterate over the selection until the method returns something != null. This way you could easily extract additional information out of the selection
MyData date = SelectionUtils.visit(selection, new Visitor<MyObject>(MyObject.class) {
MyData visit(MyObject item) {
if (item.getData() != null) return item.getData();
return null;
}
});