2

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?

Animesh Agrawal
  • 161
  • 2
  • 16

2 Answers2

4

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))
Claude Brisson
  • 4,085
  • 1
  • 22
  • 30
2

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

starwarswii
  • 2,187
  • 1
  • 16
  • 19