2 Replies Latest reply: Oct 20, 2006 6:14 AM by 807607 RSS

    static block for registering plugin

      I am developing an application where I want to be able to add plugins easily.

      I thought that I could get the plugins to register to a "PluginCenter" using static initializer/block. The problem is that the static block is not executed until the class is loaded. An the class is loaded first when referenced.

      The originial application should not have any reference to the class name of the plugin, so explicit loading of the class by name is not possible if it is not possible to find the class name using reflection (all plugins implements a common interface).

      Anyone that has an idea for a good approach for this ?
      There must exist applications/systems where plugins can be added simply by adding a jar-file with the plugin classes, how do they solve this ?

      public class PluginX implements Plugin
         PluginCenter.registerPlugin(new PluginX());
        • 1. Re: static blcok for registering plugin
          They probably solve it by defining a directory for JARs, search it, look into the JAR's manifest for some custom entry for a "start-up class" and use URLClassLoader to load it.

          The question is: once you got hold of the class: how will you use it?
          • 2. Re: static block for registering plugin
            The standard approach is a "services" file. Say your plugins are characterised by implementing org.widget.MyPluinInterface you create a text file with the path


            Each line of this file is a concrete plugin class FQN.

            The usual convention of ignoring lines starting with # applies.

            Your framework program accesses these files using getResources(). If you use a URLClassLoader to load your plugins, then call getResources() on that ClassLoader.

            The framework picks up every such file on the class path (getResources() does this), so you can have mutliple jars or directories with plugin implementations and all the concrete implementations will be picked up.

            Unfortunately there's no serive loader in the standard library (though I think there's one in one of the proprietry sun classes), but it's not hard to code.


            The service function will be in the new "Mustang" release of java when it comes out:



            Message was edited by: