HTL 访问 属性 没有 Getter

HTL Access Property Without Getter

我正在编写一个 AEM 组件,我有一个对象被返回,该对象是来自 SDK 的类型。此类型具有 public 属性但没有 getter。为简单起见,它可以这样定义:

class MyItem {
    public String prop1;
    public String prop2;
}

现在通常,我需要一个 getter,像这样:

class MyItem {
    public String prop1;
    public String prop2;

    public String getProp1() {
        return prop1;
    }
}

可是我没有这个奢侈。现在,我有一个 Java 实现,它使用另一种类型来解决这个问题,但我认为 HTL 不允许我直接访问 prop1 有点疯狂(它调用 getter).我已经查看了文档,但看不到有关如何完成此操作的任何指示。我希望能够写:

${item.prop1}

并让它访问 public 属性 而不是调用 getProp1().

这可能吗?

来自官方documentation

Once the use-class has initialized, the HTL file is run. During this stage HTL will typically pull in the state of various member variables of the use-class and render them for presentation.

To provide access to these values from within the HTL file you must define custom getter methods in the use-class according to the following naming convention:

A method of the form getXyz will expose within the HTL file an object property called xyz. For example, in the following example, the methods getTitle and getDescription result in the object properties title and description becoming accessible within the context of the HTL file:

HTL 解析器确实枚举了所有 public 属性,就像任何 java 枚举 public fuields 一样,其中包括 getter 和 public memebers。

虽然您是否应该拥有 public 变量值得怀疑,但这不是本次讨论的一部分。本质上 ot 应该像其他人指出的那样工作。

如果 public 字段是由您的 Java Use-class 声明的,则您不需要 getter。 Apache Sling 中实际上有一个测试涵盖了这种情况:

https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/testing-content/src/main/resources/SLING-INF/apps/sightly/scripts/use/repopojo.html

这也适用于从包导出的 Use-classes。

对于使用适配器模式 [0] 的吊索模型,我创建了 https://issues.apache.org/jira/browse/SLING-7075

[0] - https://sling.apache.org/documentation/bundles/models.html#specifying-an-alternate-adapter-class-since-110