java将列表项插入为属性?
目标:使用Freemarker生成以下形式的Java代码
public void save(){
helper.save();
}
public void load(){
helper.load();
}
//Other such lifecycle methods
基本上,我有一些“生命周期”方法名称,我想为它们中的每一个生成代码。但是,我只在传入的模型对象需要时生成方法。我的模型类看起来像:
public class Model{
private boolean load;
private boolean save;
//bools for other lifecycle methods
public Model(boolean load, boolean save){
this.load = load;
this.save = save;
}
public boolean getLoad(){
return load;
}
public boolean getSave(){
return save;
}
}
我的freemarker模板:
<#assign methodNames = ["load", "save"]>
<#list methodNames as method>
<#if model.method>
public void ${method}(){
helper.${method}();
}
</#if>
</#list>
但是,该<#if>
语句不起作用。Freemarker抱怨说model.method
是null
。看起来Freemarker在我的模型中查找getMethod()
,而不是将model
解析为save
或load
,然后查找getSave()
或getLoad()
我尝试了以下方法,但在所有情况下Freemarker都会抱怨一个或另一个语法错误:
<#assign methodNames = ["load", "save"]>
<#list methodNames as method>
<#assign methodRequired = r"model.${method}">
<#if <@methodRequired?interpret>>
public void ${method}(){
helper.${method}();
}
</#if>
</#list>
这失败了,错误是我不能将<@methodRequired>
放在<#if>
内。我还直接尝试了<#if model.${method}>
,但显然不起作用
为完整起见,以下是我调用模板的方式:
//Obtain a writer object first. Then ...
Model model = new Model(true, false);
myTemplate.process(model, writer);
writer.close();
因此,问题是-如何让Freemarker从另一个模型对象内部为我提供列表变量的值强>
# 1 楼答案
它与其他典型语言非常相似:
model[method]
model.method
实际上是model["method"]
的简写。你也可以写像model["foo" + someVar]
这样的东西,所以它是someContainer[someKeyExpression]