Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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:

<%= SomeClass.FixDateFormat(ViewData.Model.SomeClass.DateCreated) %> 
like image 495
Blankman Avatar asked Feb 24 '10 20:02

Blankman


People also ask

Can I call a static method inside a regular one?

A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.

How do you call a method inside a static method?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.

Can I call static method from instance?

Java syntax allows calling static methods from an instance. For example, we could create this code and it would compile and run correctly: public static void main(String args) { Example ex = new Example();

Can we call static method from child class?

If we call a static method by using the parent class object, the original static method will be called from the parent class. If we call a static method by using the child class object, the static method of the child class will be called.


2 Answers

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) )  
like image 107
Gus Avatar answered Sep 17 '22 01:09

Gus


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')) 
like image 22
Vadzim Avatar answered Sep 17 '22 01:09

Vadzim