How can code in one module be notified when other modules are loaded or unloaded?

Let's begin by stating that you probably do not need to know when other modules are loaded or unloaded. The module system takes care of dependency management for you, so your module should never be loaded unless all of its stated dependencies are loaded too.

The normal means of communicating between modules about available services (which you could consider indirect dependencies) is using the Lookup API. If what you really wanted was to know when a service became available, you do not need to listen to module load or unload events as such; which module hosts the service is not of direct interest. Instead:

  1. Define a service some.Interface in some module.
  2. Implement that interface using some.Implementation in some other module. Register it with @ServiceProvider(service=Interface.class).
  3. In some module consuming the service, use
 import some.Interface;
 // ...
 private static final Lookup.Result<Interface> services =
 static {
     services.addLookupListener(new LookupListener() {
         public void resultChanged(LookupEvent ev) {
             // some module was loaded or unloaded!
 // ...
 for (Interface service : services.allInstances()) {
     // use a currently available service

If you simply want to run some code when your module loads or unloads, registering an instance of ModuleInstall will do the trick. There is even a wizard in the IDE for setting this up.

But in the very rare case that you want to be notified when other modules are loaded or unloaded, it is possible because:

  1. You can use Lookup.Result to listen to changes in the contents of a Lookup, even the global lookup.
  2. Every module installs an instance of ModuleInfo into the default Lookup so the module system (or other code) can find out details about the module including its code name base, version numbers and display name.

By using these two facts together, it is possible to listen to changes in the installed modules by running code like this at some point in the application's lifecycle (DevFaqAppLifecycleHooks):

 final Lookup.Result<ModuleInfo> result =
 result.addLookupListener(new LookupListener() {
     public void resultChanged(LookupEvent event) {
         // it seems a module was installed or removed

Once you detect that a module has been created you may also want to register a PropertyChangeListener and listen to ModuleInfo.PROP_ENABLED. (A module present in the installation will provide a ModuleInfo but isEnabled might be false if it is not currently loaded.)

Applies to: NetBeans 6.7 and later

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo