Sling AdaptTo :
Sling offers an Adapter pattern to conveniently translate objects that implement the Adaptable interface. This interface provides a generic adaptTo() method that will translate the object to the class type being passed as the argument.
For example to translate a Resource object to the corresponding Node object, you can simply do:
Example :
Node node = resource.adaptTo(Node.
class
);
Use Cases :
There are the following use cases:
- Get implementation-specific objects.For example, a JCR-based implementation of the generic Resource interface provides access to the underlying JCR Node.
- Shortcut creation of objects that require internal context objects to be passed.For example, the JCR-based ResourceResolver holds a reference to the request's JCR Session, which in turn is needed for many objects that will work based on that request session, such as the PageManager or UserManager.
- Shortcut to services.A rare case - sling.getService() is simple as well.
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 extend SlingAdaptable (which passes the adaptTo call to a central adapter manager).
- This allows hooks into the adaptTo mechanism for existing classes, such as Resource.
No comments:
Post a Comment