Prerequisite: http://sling.apache.org/documentation/the-sling-engine/adapters.html
Use Case: You often have a case where you want to adaptTo from existing object to custom Object or Provide adapter functionality for custom object to existing object.
Solution: There are mainly two ways you can use adaptTo
Case 1: You want existing object to be adaptable to custom object. For example you have a specific kind of node and you want Node or Resource to be adaptable to this object.
CustomObject myCustomObject = resource.adaptTo(CustomObject.class)
Or
CustomObject myCustomObject = node.adaptTo(CustomObject.class)
Or
CustomObject myCustomObject = <ANY Adaptable OBJECT>.adaptTo(CustomObject.class)
Case 2: You want custom object to be adaptable to existing object. For example you have specific kind of resource and you want this to be adaptable to existing resource.
Node node = CustomObject.adaptTo(Node.class)
Or
Resource resource = CustomObject.adaptTo(Resource.class)
Or
<Any OOTB Adaptable> myObject = MycustomObject.adaptTo(<Any OOTB Adaptable>.class)
Case 1: Example
Use Case: You often have a case where you want to adaptTo from existing object to custom Object or Provide adapter functionality for custom object to existing object.
Solution: There are mainly two ways you can use adaptTo
Case 1: You want existing object to be adaptable to custom object. For example you have a specific kind of node and you want Node or Resource to be adaptable to this object.
CustomObject myCustomObject = resource.adaptTo(CustomObject.class)
Or
CustomObject myCustomObject = node.adaptTo(CustomObject.class)
Or
CustomObject myCustomObject = <ANY Adaptable OBJECT>.adaptTo(CustomObject.class)
Case 2: You want custom object to be adaptable to existing object. For example you have specific kind of resource and you want this to be adaptable to existing resource.
Node node = CustomObject.adaptTo(Node.class)
Or
Resource resource = CustomObject.adaptTo(Resource.class)
Or
<Any OOTB Adaptable> myObject = MycustomObject.adaptTo(<Any OOTB Adaptable>.class)
Case 1: Example
Here is how your CustomAdapter will look like
Case 2: Example
for this you can use slingAdaptable class https://dev.day.com/docs/en/cq/5-6/javadoc/org/apache/sling/api/adapter/SlingAdaptable.html
One example (You can find more example here) http://svn.apache.org/repos/asf/sling/trunk/bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/ResourceResolverImpl.java
In pom.xml you need following include. You can always find dependencies from HOST:PORT/system/console/depfinder
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.api</artifactId>
<version>2.2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.adapter</artifactId>
<version>2.0.10</version>
<scope>provided</scope>
</dependency>
Let me know if you have any question.
No comments:
Post a Comment