Time for action – injecting preferences

The top-level preferences store can be injected into the object by using standard dependency injection techniques, using the IEclipsePreferences interface. The underlying nodes can also be injected by using an @Preferences annotation, specifying the node path of interest.

  1. Add the org.eclipse.e4.core.di.extensions package to the manifest of the com.packtpub.e4.clock.ui project, which contains the @Preferences annotation.
  2. In the TimeZoneTreeView class, add a new field of type IEclipsePreferences called preferences. Annotate it with @Inject and @Preferences(nodePath = "com.packtpub.e4.clock.ui"):
    @Preference(nodePath = "com.packtpub.e4.clock.ui")
    @Inject
    IEclipsePreferences preferences;

    Note

    The IEclipsePreferences interface is a subtype of the Preferences interface used in the previous section. However, the @Preference annotation requires that the IEclipsePreferences type be used here; otherwise a runtime exception will occur.

  3. In the create method, print a message that reads the launchCount from the preferences as an int, defaulting to 0 if it is not found:
    @PostConstruct
    public void create(Composite parent) {
      ...
      System.out.println("Launch count is: "
       + preferences.getInt("launchCount", 0));
  4. Run the target Eclipse instance, and open the Time Zone Tree View. In the Console view, there should be an additional Launch count is: message with the same value as before.

What just happened?

The preferences are accessed through an IEclipsePreferences interface, which is a subtype of the Preferences interface. E4 injection is used to find the preferences object for the specific bundle, using the @Preferences annotation to find the preferences associated with a specific nodePath.

The convention is to use the bundle's symbolic name as the node path, which is the same as using the InstanceScope method getNode in the previous example. The preferences node can also be used to save or change values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.103.202