I am setting the data in model as:
@RequestMapping("/forms/builder/")
public void renderMethod1(Model model) {
SoyMapData x=new SoyMapData("class","menu horizontal right");
model.addAttribute("pageTitles", x);
}
Which is mapped to below function via Spring:
@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
String renderedResponse = null;
renderedResponse = compiledSoyTemplates.render(templateName, model, messageBundle);
}
Here I need to check if model is of type SoyMapData
, if yes then set the type of model to SoyMapData
else map.
How can I do this?
I have tried below approach its not working.
You can do that with the instanceof
operator:
SoyMapData soyModel;
if (model instanceof SoyMapData) {
// It is, get a reference using that type
soyModel = (SoyMapData)model;
}
...but if you need to do that, it suggests a problem with the encapsulation in the API design. Your render
method shouldn't need to know what kind of Map
it's receiving, that breaks encapsulation.
There are many ways to solve that. One is by deriving a new interface from Map
that allows render
to do its job, and then using that interface rather than Map
in the method signature. But that's only one way.
Update: Re your updated code, if I understand you correctly, you want to call compiledSoyTemplates.render
with either a SoyDataModel
argument or a Map
argument depending on whether model
is a SoyDataModel
. (E.g., it's an overloaded method and you want the compiler to know which one to use.) If so, then you just use the information I gave you above like this:
@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
String renderedResponse = null;
if (model instanceof SoyDataModel) {
renderedResponse = compiledSoyTemplates.render(
templateName,
(SoyDataModel)model,
messageBundle
);
}
else {
renderedResponse = compiledSoyTemplates.render(
templateName,
model,
messageBundle
);
}
}