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
  • 151
  • 2
  • 15

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
  • 3,680
  • 1
  • 24
  • 27
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
  • 1,827
  • 1
  • 15
  • 14