Caching
To improve performance, implementations are free to cache the object returned from a obj.adaptTo()
call. If the obj
is the same, the returned object is the same.
This caching is performed for all AdapterFactory
based cases.
However, there is no general rule - the object could be either a new instance or an existing one. This means that you cannot rely on either behavior. Hence it is important, especially inside AdapterFactory
, that objects are reusable in this scenario.
How it works
There are various ways that Adaptable.adaptTo()
can be implemented:
-
By the object itself; implementing the method itself and mapping to certain objects.
-
By an
AdapterFactory
, which can map arbitrary objects.The objects must still implement the
Adaptable
interface and must extendSlingAdaptable
(which passes theadaptTo
call to a central adapter manager).This allows hooks into the
adaptTo
mechanism for existing classes, such asResource
. -
A combination of both.
For the first case, the Java™ docs can state what adaptTo-targets
are possible. However, for specific subclasses such as the JCR-based Resource, often this is not possible. In the latter case, implementations of AdapterFactory
are typically part of the private classes of a bundle and thus not exposed in a client API, nor listed in Java™ docs. Theoretically, it would be possible to access all AdapterFactory
implementations from the OSGi service runtime and look at their “adaptables” (sources and targets) configurations, but not to map them to each other. In the end, this depends on the internal logic, which must be documented. Hence this reference.