public class Injector extends Object
A tiny dependency injection and plugin helper for Robolectric.
Dependencies may be retrieved explicitly by calling
getInstance(java.lang.Class<T>); transitive dependencies will be automatically injected as needed. For a given injector, all calls to
getInstance(java.lang.Class<T>) are idempotent.
Dependencies are identified by an interface or class, and optionally by a name specified with
When a dependency is requested, an implementation is sought.
The injector looks for any instance that has been previously found for the given interface, or that has been explicitly registered with
Injector.Builder.bind(Class, Object) or
Builder#bind(Key, Object). If none is found, the injector searches for an implementing class from the following sources, in order:
Collection, then its component type is recursively sought using
PluginFinder.findPlugins(Class)and an array or collection of those instances is returned.
ServiceLoaderservices under the dependency type (see also
If the injector has a superinjector, it is always consulted first (with the exception of interfaces annotated
AutoFactory; see Scopes below).
If no implementing class is found in the injector or any superinjector, an exception is thrown.
When the injector has determined an implementing class, it attempts to instantiate it. It searches for a constructor in the following order:
Inject. (If multiple constructors are
@Injectannotated, the injector will throw an exception.)
Any constructor parameters are treated as further dependencies, and the injector will recursively attempt to resolve an implementation for each before invoking the constructor and thereby instantiating the original dependency implementation.
If the dependency type is an interface annotated
AutoFactory, then a factory object implementing that interface is created; a new scoped injector is created for every method call to the factory, with parameter arguments registered on the scoped injector.
All methods are MT-safe.
|Modifier and Type||Class and Description|
Identifies an injection point.
|Constructor and Description|
Creates a new empty injector.
|Modifier and Type||Method and Description|
Finds an instance for the given class.
@Nonnull public <T> T getInstance(@Nonnull Class<T> type)
Finds an instance for the given class. Calls are guaranteed idempotent.
public Injector.Builder newScopeBuilder(ClassLoader classLoader)