velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Lawrence.Si...@MSCsoftware.com
Subject Re: creating new instances
Date Sat, 04 Sep 2004 14:57:53 GMT
We are writing Velocity (actually DVSL) macros for a framework in which we 
have no access to any of the Java source code.  I'm looking for a hack 
that will allow me to create instances of classes that I write myself and 
place in the classpath.

Larry Siden, IBS consultant, Viper team
x72612



Shinobu Kawai <shinobu.kawai@gmail.com> 
09/04/2004 10:52 AM
Please respond to
"Velocity Users List" <velocity-user@jakarta.apache.org>


To
Velocity Users List <velocity-user@jakarta.apache.org>
cc

Subject
Re: creating new instances






Hi Larry,

> Is it possible to create new instances of a class from a velocity
> template?  I'd like to do something like "#set($foo =
> com.foo.bar.class.getConstructor().newInstance())".  I know that doesn't
> work, but is there another way to achieve that?
Just out of curiosity, why do you want to do that?

Anyways, you can use reflection, I guess.

In java:
context.put("classes", this.getClass());
context.put("bar", "Larry");

In the template:
#set($foo = $classes.forName("java.lang.StringBuffer").newInstance())
$foo.append("Hello ").append($bar).append("!")

And you will get:
Hello Larry!

Best regards,
-- Shinobu Kawai

-- 
Shinobu Kawai(shinobu.kawai@gmail.com)

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org



Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message