Sling Model Dynamic Adaptation | Community
Skip to main content
Level 2
May 21, 2019
Solved

Sling Model Dynamic Adaptation

  • May 21, 2019
  • 1 reply
  • 2456 views

I have a special node named “form” in my content structure. This form node has a child node called “items” .Under this items node the content manager can add any component from a group of components. Each of this component resources can be adapted to a sling model class (every model class is a child class of a common base class)

Component A Adapt to Model A (extends BaseModel)

Component B Adapt to Model B (extends BaseModel)

Component C Adapt to Model C (extends BaseModel)

I also have another model class for the “form” resource. Inside this class I Iterate the “items” resource and check the resourceType property to decide which class to be used to adapt the resource.

At the moment I have more than 12  if else branching for this  and I am afraid that this will grow as the project proceed with new requirements.

Could you please advise me what the best way of doing such things is?

Regards

Denny

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Peter_Puzanovs

Hi Denny,

You can store the class to be adapted to inside the resource metadata as a String and use https://sling.apache.org/apidocs/sling7/org/apache/sling/commons/classloader/DynamicClassLoaderManager.html​ to get ClassLoader and load the class, then cache response in a map once resolved.

This works well when all your classes are inside the same bundle and their names are unique across your bundles.

Regards,

Peter

1 reply

Peter_Puzanovs
Community Advisor
Peter_PuzanovsCommunity AdvisorAccepted solution
Community Advisor
May 21, 2019

Hi Denny,

You can store the class to be adapted to inside the resource metadata as a String and use https://sling.apache.org/apidocs/sling7/org/apache/sling/commons/classloader/DynamicClassLoaderManager.html​ to get ClassLoader and load the class, then cache response in a map once resolved.

This works well when all your classes are inside the same bundle and their names are unique across your bundles.

Regards,

Peter