简体   繁体   English

如何在FreeMarker(FTL)中从自己的类创建实例

[英]How can I create an instance from a own class in FreeMarker (FTL)

I wish to instantiate a java class that I have defined in my domain and I want to use it from my FTL code in this way, but I'm getting an error. 我想实例化我在域中定义的java类,并希望以这种方式从我的FTL代码中使用它,但是我遇到了错误。

<#assign myClassInstance = "com.domain.MyClass"?new())>

Is it possible? 可能吗? What I should change to do it? 我应该改变做些什么?

MyClass doesn't implements the TemplateModel MyClass没有实现TemplateModel

Thanks! 谢谢!

There's no built-in function for instantiating arbitrary non- TemplateModel classes... maybe there should be a setting to allow that for ?new . 没有用于实例化任何非TemplateModel类的内置函数...也许应该有一个设置允许?new Anyway, for now you can write a TemplateMethodModelEx that does that, and then you can pull that into some of your commonly included/imported templates like <#assign unrestrictedNew = "com.example.UnrestrictedNewMethodModel"?new()> (or just put the instance into the data-model or into the Configuration as a shared variable) and then you can do <#assign myClassInstance = unrestrictedNew("com.domain.MyClass")(arg1, arg2, argN)> in your templates. 无论如何,现在您可以编写一个执行该操作的TemplateMethodModelEx ,然后将其拉入一些常见的包含/导入的模板中,例如<#assign unrestrictedNew = "com.example.UnrestrictedNewMethodModel"?new()> (或仅放入将实例作为数据共享到数据模型或作为共享变量放入Configuration ),然后可以在<#assign myClassInstance = unrestrictedNew("com.domain.MyClass")(arg1, arg2, argN)>执行<#assign myClassInstance = unrestrictedNew("com.domain.MyClass")(arg1, arg2, argN)> There are two tricky parts in implementing such a TemplateMethodModel . 实现这样的TemplateMethodModel有两个棘手的部分。 One is resolving the class name to a Class , for which I recommend env.getNewBuiltinClassResolver().resolve(className, env, null) , where env is the current freemarker.core.Environment object. 一种是将类名称解析为Class ,我建议env.getNewBuiltinClassResolver().resolve(className, env, null) ,其中env是当前的freemarker.core.Environment对象。 The other is calling the constructor, as then you have to convert parameter values and possibly chose an overloaded constructor. 另一种是调用构造函数,因为那样您就必须转换参数值并可能选择了一个重载的构造函数。 For that I recommend calling ow = env.getObjectWrapper() , see if ow instanceof BeansWrapper (throw exception if it isn't), then do return ((BeansWrapper) ow).newInstance(cl, arguments) . 为此,我建议调用ow = env.getObjectWrapper() ,查看ow instanceof BeansWrapper (如果不是,则抛出异常),然后return ((BeansWrapper) ow).newInstance(cl, arguments)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM