FreeMarker調用JAVA靜態方法

來源:互聯網
上載者:User
官方文檔地址:
http://freemarker.sourceforge.net/docs/pgui_misc_beanwrapper.html#autoid_54 Accessing static methods

The TemplateHashModel returned from BeansWrapper.getStaticModels() can be used to create hash models for accessing static methods and fields of an arbitrary class.

BeansWrapper wrapper = BeansWrapper.getDefaultInstance();TemplateHashModel staticModels = wrapper.getStaticModels();TemplateHashModel fileStatics =    (TemplateHashModel) staticModels.get("java.io.File");  

And you will get a template hash model that exposes all static methods and static fields (both final and non-final) of the java.lang.System class as hash keys. Suppose that you put the previous model in your root model:

root.put("File", fileStatics);  

From now on, you can use ${File.SEPARATOR} to insert the file separator character into your template, or you can even list all roots of your file system by:

<#list File.listRoots() as fileSystemRoot>...</#list>  

Of course, you must be aware of the potential security issues this model brings.

You can even give the template authors complete freedom over which classes' static methods they use by placing the static models hash into your template root model with

root.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());  

This object exposes just about any class' static methods if it's used as a hash with class name as the key. You can then use expression like ${statics["java.lang.System"].currentTimeMillis()} in your template. Note, however that this has even more security implications, as someone could even invoke System.exit() using this model if the method exposure level is weakened to EXPOSE_ALL.

Note that in above examples, we always use the default BeansWrapper instance. This is a convenient static wrapper instance that you can use in most cases. You are also free to create your own BeansWrapper instances and use them instead especially when you want to modify some of its characteristics (like model caching, security level, or the null model representation).

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.