これが解決可能な問題であるかどうかはまったくわかりませんが、フリーマーカー テンプレートがあると仮定すると、テンプレートが使用する変数を問い合わせることができるようにしたいと思います。
私の目的のために、freemarker テンプレートは非常に単純で、「ルート レベル」のエントリのみであると想定できます (このようなテンプレートのモデルは単純なマップになります)。言い換えると、ネストされた構造などを必要とするテンプレートを処理する必要はありません。
ベストアンサー1
Javaから変数を取得するもう1つの方法。これはテンプレートを処理し、InvalidReferenceException
freemarker-template内のすべての変数を見つけるためにキャッチするだけです。
/**
* Find all the variables used in the Freemarker Template
* @param templateName
* @return
*/
public Set<String> getTemplateVariables(String templateName) {
Template template = getTemplate(templateName);
StringWriter stringWriter = new StringWriter();
Map<String, Object> dataModel = new HashMap<>();
boolean exceptionCaught;
do {
exceptionCaught = false;
try {
template.process(dataModel, stringWriter);
} catch (InvalidReferenceException e) {
exceptionCaught = true;
dataModel.put(e.getBlamedExpressionString(), "");
} catch (IOException | TemplateException e) {
throw new IllegalStateException("Failed to Load Template: " + templateName, e);
}
} while (exceptionCaught);
return dataModel.keySet();
}
private Template getTemplate(String templateName) {
try {
return configuration.getTemplate(templateName);
} catch (IOException e) {
throw new IllegalStateException("Failed to Load Template: " + templateName, e);
}
}