Animesh Agrawal
Animesh Agrawal

Reputation: 161

Is there any way to cast an object in velocity?

I am using velocity template to generate some string and passing object type to context.

I wanted to cast that object to specific class is there any way to achieve this?

Upvotes: 2

Views: 4104

Answers (2)

starwarswii
starwarswii

Reputation: 2417

Claude Brisson's answer works, but from Velocity 1.6 and upwards, it can be done a little simpler and without using Class.forName() which can create dependencies on classes that are invisible at compile time.

Let's say I wanted to cast something to a String. In Java:

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

Then in Velocity I can use:

#set($casted = $String.cast($sourceObject))

Source

Upvotes: 2

Claude Brisson
Claude Brisson

Reputation: 4130

Generally, you would handle such tasks on the Java side, not on the template side.

Nevertheless, if you're not using a SecureUberspector, it's doable (but really hackish...):

#set($casted = $someObject.class.forName('target.class.name').cast($sourceObject))

Upvotes: 4

Related Questions