Java 从速度视图页面内部调用类方法(静态)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2329191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling class methods (static) from inside a velocity view page
提问by Blankman
Can you call class methods from inside a view page?
您可以从视图页面内部调用类方法吗?
Specifically ones that are not passed into the view?
特别是那些没有传递到视图中的?
In asp.net MVC I can do this:
在 asp.net MVC 中,我可以这样做:
<%= SomeClass.FixDateFormat(ViewData.Model.SomeClass.DateCreated) %>
回答by Gus
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)
(在这里找到:http: //velocity.10973.n7.nabble.com/Use-of-static-functions-td15126.html)
in Velocity 1.5 or earlier, you can just use:
在 Velocity 1.5 或更早版本中,您可以使用:
#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.util.Math),我们在 1.6 中添加了对无实例静态类方法的支持:
Java:
爪哇:
context.put("String", String.class);
Velocity:
速度:
#set( $foo = $String.format('%.1f', $dataFedIn) )
回答by Vadzim
Here is a universal way to call any static method of any class without need for preliminarily context manipulation:
这是调用任何类的任何静态方法而无需初步上下文操作的通用方法:
#??set($str='test')##
#set($Base64=$str.class.forName('java??.util.Base64'))##
?$Base64.getEncoder()??.encodeToString($str??.getBytes('utf8'))