StringTemplate 允许程序员通过 getter(不带参数的函数)获取数据。
我想知道是否可以使用字符串模板中的参数调用Java函数?
有一个解决方法是滥用字典。这是一个实现“函数”的示例,用于限制列表中的项目数量(github 上的问题 https://github.com/antlr/stringtemplate4/issues/197).
在您的代码中添加字典:
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.");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)