How to check the map type?
-
09-02-2021 - |
Question
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.
Solution
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
);
}
}
OTHER TIPS
You cannot change the type of a variable/parameter in Java. You can check the type of the object, and if it matches your criteria, create another variable of the new type as follows
if (model instanceof SoyMapData) {
SoyMapData soyModel = (SoyMapData)model;
...
}
Edit:: SoyMapData
is placed inside model
in renderMethod1
. If the parameter model
in renderMergedTemplateModel
references the same object (then Model
needs to implement the interface Map
) you need to get the object at the key pageTitles
.
If the above assumptions hold,
if (model.get("pageTitles") instanceof SoyMapData) {
SoyMapData sModel = (SoyMapData)model.get("pageTitles");
}
should work.
instanceof
is used to check the runtime type of an instance:
if (model instanceof SoyMapData) {
SoyMapData sData = (SoyMapData)model;
...
} else {
...
}