Expand my Community achievements bar.

SOLVED

Sling Model Dynamic Adaptation

Avatar

Level 3

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

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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/DynamicClassLoaderManag...​ 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

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

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/DynamicClassLoaderManag...​ 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