-1

I have two java packages - package-A, package-B Let us say this is the dependency chains of the packages.

package-A -> package-B

I want to pass custom Java function that would be executed in package-A. How do I do that?

package-A 
   - src
       - Foo.java

package-B
   - src
       - Bar.java
       - Tag.java
class Foo implements Tag {
  doThis() {
       // do what I say.
  }
}

------------------------------------------
class Bar {
    execute() {
        tag.doThis();
    }
}

interface Tag {
  doThis();
}

I want some sort of plugin framework, so that package-A owners can provide an implementation to all users of library package-B without package-B having to depend on package-A

mak
  • 37
  • 8

1 Answers1

1

OSGi has a service registry. A plugin (a bundle) can register a service object under its interface name. Other plugins can get that service. For example, in Tag.java we have:

  public interface Tag { void doThis(); }

The provider of the service can provide an implementation as follows:

@Component
public class Foo implements Tag {
  @Override
  public void doThis() { System.out.println("do what I say"); }
}

The @Component annotation is defined by OSGi. When the program starts, it will register a Tag service.

The next part is the consumer in Bar.java:

@Component
public class Bar {
    @Activate public Bar( @Reference Tag tag) { tag.doThis(); }
}

The @Component will create an instance of Bar and will pass an instance of the Tag service to the constructor because it has a @Activate and @Reference annotation.

As a tip, you want to package the consumer, the interface, and the provider in three different bundles.

A simple example of this pattern is shown in a bndtools video

Peter Kriens
  • 15,196
  • 1
  • 37
  • 55