API / Apache FreeMarker Interview questions
How do you access static Java members (static methods, fields, and enum constants) from a FreeMarker template?
Static members are not reachable by default - MyClass.CONSTANT style access has to be deliberately turned on, which is part of FreeMarker's security model. The usual approach uses BeansWrapper's static-model support:
BeansWrapper bw = new BeansWrapperBuilder(Configuration.VERSION_2_3_32).build(); TemplateHashModel staticModels = bw.getStaticModels(); configuration.setSharedVariable("statics", staticModels);
Once exposed this way, a template can reach a static field or call a static method by naming the fully-qualified class inside the statics hash:
${statics["java.lang.Math"].PI} ${statics["com.example.util.PriceUtil"].round(total)}
Enum constants are handled the same way through bw.getEnumModels(), exposed under a separate shared variable such as enums. Because this access is opt-in and must be wired up explicitly by application code, a template cannot reach static members of arbitrary classes unless the application chose to expose exactly that class.
More Related questions...