Displaying a message to System.out
shows that the command works, but what if the command needed to pick up a local state? Fortunately, the @Named
and @Inject
annotations allow objects to be injected into the method when it is called.
hello()
method so that instead of printing a message to System.out
, it opens a dialog window, using the active shell:public void hello(@Named(IServiceConstants.ACTIVE_SHELL) Shell s){ MessageDialog.openInformation(s, "Hello World", "Welcome to Eclipse 4 technology"); }
IEclipseContext
interface. For example, using the math.random
function from earlier, a value could be injected into the handler like this:public void hello(@Named(IServiceConstants.ACTIVE_SHELL) Shell s, @Named("math.random") double value) {
helloCommand
to add a parameter, by opening the Application.e4xmi
and navigating to the Application | Commands | helloCommand, right-click and go to Add child | Command Parameter to add a command parameter:com.packtpub.e4.application.commandparameter.hello.value
hello.value
Application.e4xmi
and navigate to Application | Windows | Main Menu | Menu (File) | HandledMenuItem (Hello) | Parameters. Right-click and go to Add child | Parameter to create a parameter:com.packtpub.e4.application.parameter.hello.value
com.packtpub.e4.application.commandparameter.hello.value
Hello World Parameter
public void hello(@Named(IServiceConstants.ACTIVE_SHELL) Shell s, @Optional @Named("com.packtpub.e4.application.commandparameter.hello.value") String hello) @Named("math.random") double value) { MessageDialog.openInformation(s, "Hello World", hello+value); } }
Any values can be injected into the method when it is invoked, provided that they are available in the context when the handler is called. These can be taken from standard constants (such as those in IServiceConstants
) or be custom values injected at runtime. Other values include:
ACTIVE_WINDOW
: The currently displayed windowACTIVE_PART
: The currently selected partACTIVE_SELECTION
: The current selectionIf the values are one of a set of values, they can be encoded in the menu or other command invocation. They can also be set via code which calls IEclipseContext.set()
with an appropriate value.