Eclipse Action with Generics
I wrote this code a couple of weeks ago. It’s a nice idea on how to use generics in order to reduce the pain of using the Eclipse API.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
public abstract class TypedAction<T> implements IObjectActionDelegate {
protected List<T> selectedElements = new ArrayList<T>();
protected Shell shell;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
this.shell = targetPart.getSite().getShell();
}
public void run(IAction action) {
for (T element : selectedElements) {
runOn(element, action);
}
}
protected abstract void runOn(T selectedElement, IAction action);
public void selectionChanged(IAction action, ISelection selection) {
selectedElements.clear();
boolean enabled = false;
if (selection instanceof StructuredSelection) {
enabled = true;
for (Iterator it = ((StructuredSelection) selection).iterator(); it.hasNext();) {
try {
T selectedElement = (T) it.next();
selectedElements.add(selectedElement);
} catch (ClassCastException e) {
enabled = false;
break;
}
}
}
action.setEnabled(enabled);
}
} Try to refactor your actions to extend this class and you will find a significant reduction in code size.