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

前端 未结 2 1813
天命终不由人
天命终不由人 2020-12-10 10:47

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:

<         


        
相关标签:
2条回答
  • 2020-12-10 11:51

    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'))
    
    0 讨论(0)
  • 2020-12-10 11:53

    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) ) 
    
    0 讨论(0)
提交回复
热议问题