I am developing a library in Java where I want other Java codes to be able hook at various life-cycle.

The approach I am thinking of is define various Interfaces (for the the different hook points). At runtime discover all implementors of those classes (which are already available in classpath). Run them at the appropriate time. I could use probably use Reflections for this.

Problem with using Reflections is I am dictating an approach.

Another approach could be that I have optional dependency on these interfaces and use dependency injection (like Dagger) to inject an instance. The code using this library can then inject a concrete class which does all the Reflections magic described above and provide the functionality described there; if needed. This approach seems more flexible to me.

Please suggest if there are any other better approaches available?


You should look into a system like HK2 (https://hk2.java.net/2.5.0-b30/). It is specifically designed to allow for service lookups and is dynamic for runtime enablement and disablement of code. It is used for WebLogic kernel, GlassFish kernel and Jersey kernel so it is well supported. It provides both a registry type interface (ServiceLocator) and a fully functioning DI system, including eventing, interception and many other features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.