aemslingsling-models

AEM : How to get list of registered sling models using resource type


While creating a sling model we can register it through a resource type. Is there any way through which we can get the sling model class name by providing resource type in AEM. For example : if i have a resource type /mysite/component/breadcrumb and sling model is BreadCrumbModel.java . Is there OOTB service through which if i pass the resourceType value and get the class refernece.

Thanks


Solution

  • Yes, from either the provided Resource or SlingHttpServletRequest of the resource.

    modelFactory.getModelFromResource(resource)
    modelFactory.getModelFromRequest(request)
    

    ModelFactory API Docs

    Usage example: If SlingScriptHelper is injected in your class -

    Resource resource = resourceResolver.getResource("/mysite/component/breadcrumb");
    slingScriptHelper.getService(ModelFactory.class).getModelFromResource(resource);
    

    or if you already have ModelFactory injected and available, use it directly.