Executing a command programmatically

Executing a command programmatically  as described in http://www.vogella.com/articles/EclipseCommandsAdvanced/article.html#commmands_code does not work anymore in Eclipse 4. The ECommandService and EHandlerService make it possible to achieve the same result with a few more lines of code.

The following code snippet could be a part providing a welcome screen with shortcuts to several actions defined as commands, like opening the about dialog.

import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.core.commands.EHandlerService;

public class WelcomeScreen {

  @Inject
  private ECommandService commandService;

  @Inject
  private EHandlerService handlerService;

  @Inject
  public init(Composite parent) {
    // ... do something
    String command = "org.eclipse.ui.help.aboutAction"
    executeCommand(command);
    // ... do something
  }

  private void executeCommand(String command) {
    Command cmd = commandService.getCommand(command);
    ParameterizedCommand pCmd = new ParameterizedCommand(cmd, null);
    if (handlerService.canExecute(pCmd)) {
      handlerService.executeHandler(pCmd);
    }
  }
}

Another way of achieving the same is described at http://wiki.eclipse.org/E4/Snippets#Execute_Command.2FHandler_manually

2 Gedanken zu „Executing a command programmatically“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Time limit is exhausted. Please reload the CAPTCHA.