title: Create an object within a velocity template
body: <p>I've looked at this question already, but it's talking about liferay-velocity and seems to have access to this '$portal' object that I don't have access to.</p>
  
  <p><a href="https://stackoverflow.com/questions/9826547/create-object-in-velocity-template">Create object in velocity template</a></p>
  
  <p>Specifically I'm trying to create a Locale object within the template to pass it into a $dateTool.format call to get the output in a specific language.</p>
  
  <p>I can't create the locale object and pass it into the template beforehand because that code could call a variety of templates, each of which could be in different languages.</p>
  
  <p>I've tried</p>
  
  <pre><code>#set($localeClass = $portal.getClass().forName("java.util.Locale"))
  $localeClass.getName
  </code></pre>
  
  <p>but that just output '$localeClass.getName' (I wasn't sure if $portal was some magic pre-set variable or something).</p>
  
  <p>I also tried</p>
  
  <pre><code>#set($localeClass = java.util.Locale.class)
  $localeClass.getName
  </code></pre>
  
  <p>but that gave me a runtime exception when I tried to process the template.</p>
  
  <p>I saw the <a href="http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/ClassTool.html" rel="nofollow noreferrer">ClassTool</a> present in Velocity, but that doesn't support reflexive execution of code. I guess I could try something like <code>$classTool.inspect("java.util.Locale").getType.getConstructor([$classTool.inspect("java.util.String"),$classTool.inspect("java.util.String")]).newInstance(["es","ES"])</code>. </p>
  
  <p>I'll try that out, but in the meantime I'll see if anyone else has a better idea.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Since posting, I realized that velocity has a ConversionTool (which wasn't listed on their GenericTool overview page), that has a toLocale function I can call. So I can use</p>
  
  <pre><code>$dateTool.format('dd-MMM-yyyy', $date, $conversionTool.toLocale("es_ES"))
  </code></pre>
  
  <p>But I'm still curious if there was a way to accomplish this via reflection.</p>