public class DurianPlugins extends Object
A programmatic and pluggable implementation of public static final
.
To write code that requires an instance of IPlugin
, you write something like this:
IPlugin instance = DurianPlugins.get(IPlugin.class, defaultImplementation);
Once someone has requested a class from DurianPlugins, whatever instance was returned will continue to be returned for every future call. This has the same behavior as if you declared a public static final IPlugin
.
Before the value has been requested, it can be set programmatically using register(java.lang.Class<T>, T)
, or by setting a system property. This allows setting global behaviors appropriate for diverse environments.
This eternal instance for a given class is determined in this order:
register(java.lang.Class<T>, T)
durian.plugins.{pluginClass.getCanonicalName()}
is set to the fully-qualified name (Class.getName()
) of an implementation class with a no-argument constructor, then an instance of that class will be instantiated and used as the plugin implementationdefaultImplementation
that was specified in the first call to get()This class was inspired by RxJava’s RxJavaPlugins. Many thanks to them!
Modifier and Type | Field and Description |
---|---|
static String |
PROPERTY_PREFIX
Prefix to system property keys for specifying plugin classes.
|
Modifier and Type | Method and Description |
---|---|
static <T> T |
get(Class<T> pluginClass,
T defaultImpl)
Returns an instance of pluginClass which is guaranteed to be identical throughout the runtime existence of this library.
|
static <T> void |
register(Class<T> pluginClass,
T pluginImpl)
Registers an implementation as a global override of any injected or default implementations.
|
public static final String PROPERTY_PREFIX
Prefix to system property keys for specifying plugin classes.
public static <T> void register(Class<T> pluginClass, T pluginImpl) throws IllegalStateException
Registers an implementation as a global override of any injected or default implementations.
pluginClass
- The interface which is being registered.pluginImpl
- The implementation of that interface which is being registered.IllegalStateException
- If called more than once or if a value has already been requested.public static <T> T get(Class<T> pluginClass, T defaultImpl)
Returns an instance of pluginClass which is guaranteed to be identical throughout the runtime existence of this library. The returned instance is determined by:
register(java.lang.Class<T>, T)
durian.plugins.{pluginClass.getCanonicalName()}
is set to the fully-qualified name (Class.getName()
) of an implementation class with a no-argument constructor, then an instance of that class will be instantiated and used as the plugin implementationdefaultImplementation
that was specified in the first call to get()pluginClass
- The interface which is being requested.defaultImpl
- A default implementation of that interface.