Reputation: 25
I want to get a variable's class type in freemarker, used var.class.simpleName
;
but if var is a Map, freemarker will process class as a key to find value in var.
it throw exception. how can I do this ? thanks for any suggestion.
Upvotes: 0
Views: 383
Reputation: 31112
First I have to ask why do you need that, because FreeMarker templates aren't supposed to know even if var
is Map
at all. Maybe your data-model is not what the template needs.
Anyway, for now, I would write a custom TemplateMethodModelEx
for this purpose, something that you can use like ${classOf(var)}
. Inside the TemplateMethodModelEx
implementation you will receive a TemplateModel
as the argument value, and then you can check if it's an AdapterTemplateModel
, and if so you can get back the original object and get its class. (If it's not a AdapterTemplateModel
, then it perhaps isn't even a wrapped Java object, so it doesn't make sense to ask what the class of the original object is.) However, the DefaultObjectWrapper
with incompatibleImprovements
set to less than 2.3.22 doesn't give AdapterTemplateModel
to wrapped Map
-s... so in 2.3.21 you will still have to use BeansWrapper
, but you can at least set simpleMapWrapper
to true
.
In 2.3.22 it will be actually possible to write ${var?api.class}
... you might use the nightly build. Though it only supposed to solve the problem where you can't access business methods because the primary type of the business class is Map
.
Upvotes: 1