为什么 ContentFragment.adaptTo() 返回 null?

问题描述

我想创建一个可以改编自com.adobe.cq.dam.cfm.ContentFragment自定义吊索模型 如下图,

import com.adobe.cq.dam.cfm.ContentFragment;

@Model(adaptables = ContentFragment.class,adapters = EventInfo.class)
public class EventInfoImpl implements EventInfo{
  @Self
  ContentFragment cf;
  
  @Override
  public String getTitle(){
    return cf.getElement("title").getContent();
  }
}

但是在调用者类中,

EventInfo e = contentFragment.adaptTo(EventInfo.class);

adaptTo() 返回空值。(变量“e”为空)

为什么adaptTo() 返回null?以及在这种情况下我如何正确适应?

解决方法

Sling 模型只能从 Resource 或 SlingHttpServletRequest 改编。对于其他任何事情,您都需要一个经典的 AdapterFactory。

https://sling.apache.org/apidocs/sling11/org/apache/sling/api/adapter/AdapterFactory.html

How to implement a custom AdapterFactory for Sling Resource?


在ModelAdapterFactory的Sling源码中可以看到。有 createModel 方法:

<ModelType> ModelType createModel(@NotNull Object adaptable,@NotNull Class<ModelType> type)

https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/main/java/org/apache/sling/models/impl/ModelAdapterFactory.java

如果你深入挖掘,真正的过滤发生在辅助类 AdapterImplementations(第 258-268 行)

https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/main/java/org/apache/sling/models/impl/AdapterImplementations.java

     if (adaptableType == Resource.class) {
         map = resourceTypeMappingsForResources;
         resourceTypeRemovalLists = resourceTypeRemovalListsForResources;
     } else if (adaptableType == SlingHttpServletRequest.class) {
         map = resourceTypeMappingsForRequests;
         resourceTypeRemovalLists = resourceTypeRemovalListsForRequests;
     } else {
         log.warn("Found model class {} with resource type {} for adaptable {}. Unsupported type for resourceType binding.",new Object[] { clazz,resourceType,adaptableType });
         return;
     }