Calling class methods (static) from inside a velocity view page

有些话、适合烂在心里 提交于 2019-11-29 05:38:20

Since this came up in the top of my google search on this topic it seems like folks might like to see an updated answer when they get this on the top of their search...

(found this here: http://velocity.10973.n7.nabble.com/Use-of-static-functions-td15126.html)

in Velocity 1.5 or earlier, you can just use:

#set( $String = '' )
#set( $foo = $String.format('%.1f', $dataFedIn) )

because you can always call static methods on instances. :)

however, since there are some static classes of which you cannot create instances (e.g. java.util.Math), we added support in 1.6 for static class methods sans instances:

Java:

context.put("String", String.class);

Velocity:

#set( $foo = $String.format('%.1f', $dataFedIn) ) 

Here is a universal way to call any static method of any class without need for preliminarily context manipulation:

#set($String='')##
#set($Base64=$String.class.forName('java‌​.util.Base64'))##
#‌​set($str='test')##
​$Base64.getEncoder()‌​.encodeToString($str‌​.getBytes('utf8'))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!