4

StringTemplate 允许程序员通过 getter(一个没有参数的函数)获取数据。

我想知道是否可以使用字符串模板中的参数调用 Java 函数?

4

1 回答 1

0

通过滥用字典有一种解决方法。这是一个实现“功能”以限制列表中项目数的示例(github 上的问题)。

在您的代码中添加字典:

group.defineDictionary("max", new MaxListItemsLimiter());

用法(在此示例中,数组中的第一项是最大项数):

<max.(["50",myObject.items]):{msg|<msg.something>}>

final class MaxListItemsLimiter extends AbstractMap<String, Object> {

    @Override
    public Object get(Object key) {
        List items = (List) key;
        if (!items.isEmpty()) {
            //First item is max. count
            Integer limit = NumberUtils.toInt(items.get(0).toString(), -1); //use Integer.parseInt
            if (limit != -1) {
                return items.subList(1, Math.min(items.size(), limit + 1));
            } else {
                throw new AssertionError("First parameter in max must be number");
            }
        } else {
            return super.get(key);
        }
    }

    @Override
    public Set<Map.Entry<String, Object>> entrySet() {
        return Collections.emptySet();
    }

    @Override
    public boolean containsKey(Object key) {
        if (key instanceof List) {
            return true;
        } else {
            throw new AssertionError("You can use max only on Lists.");
        }
    }
}
于 2018-03-06T07:40:29.613 回答