velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Shinobu Kawai <shinobu.ka...@gmail.com>
Subject Re: creating new instances
Date Sat, 04 Sep 2004 14:52:43 GMT
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
View raw message