根据 Lars Vogel 的说法,推荐的方法是注入如下所示的服务(这对我有用)。唯一的障碍是根据插件规则,包 org.eclipse.e4.core.commands 似乎无法访问(可能尚未导出)。
但这有效:
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.core.commands.EHandlerService;
public class MyPart{
public static final String S_CMD_MY_COMMAND_ID = "my.command";
@Inject ECommandService commandService;
@Inject EHandlerService service;
@PostConstruct
public void createComposite(Composite parent) {
parent.setLayout(new GridLayout(2, false));
....
Button btnMyButton = new Button(parent, SWT.NONE);
btnMyButton.addSelectionListener(new SelectionAdapter() {
@SuppressWarnings({ "restriction" })
@Override
public void widgetSelected(SelectionEvent e) {
try {
Command command = commandService.getCommand( S_CMD_MY_COMMAND_ID );
if( !command.isDefined() )
return;
ParameterizedCommand myCommand = commandService.createCommand(S_CMD_MY_COMMAND_ID, null);
service.activateHandler(S_CMD_MY_COMMAND_ID, new MyCommandHandler());
if( !service.canExecute(myCommand ))
return;
service.executeHandler( myCommand );
} catch (Exception ex) {
throw new RuntimeException("command with id \"my command id\" not found");
}
}
});
....
}
该处理程序将按如下方式实现(不包含在适当的命令插件扩展中,除非您还希望它实现 IDefaultHandler 以实现兼容性):
public class MyCommandHandler{
@Execute
public Object execute() throws ExecutionException {
System.out.println("Hello");
return null;
}
@CanExecute
public boolean canExecute() {
return true;
}
}
详情见:
http ://www.vogella.com/articles/Eclipse4Services/article.html
https://groups.google.com/forum/#!topic/vogella/n5ztV-8GmkU