Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Java (http://www.velocityreviews.com/forums/f30-java.html)
-   -   Re: Class.forname() vs clone() (http://www.velocityreviews.com/forums/t123760-re-class-forname-vs-clone.html)

iksrazal 06-27-2003 03:03 PM

Re: Class.forname() vs clone()
 
ratisher@best.com (Mitch Ratisher) wrote in message news:<a1e74d1.0306270034.52ada381@posting.google.c om>...
> iksrazal@terra.com.br (iksrazal) wrote in message news:<850ed936.0306260444.14dae99a@posting.google. com>...
> > ratisher@best.com (Mitch Ratisher) wrote in message news:<a1e74d1.0306251418.6f98337a@posting.google.c om>...
> > > I'm not quite sure what you are trying to do, but the way I've done
> > > factories is to load a Map with Class objects when the factory is
> > > created. Then all you have to do is pass the Map whatever you mapped
> > > the class to, and call newInstance() on the Class object.
> > >

> >
> > Could you post some code? I've seen maps of objects using clone, and
> > passing a class name string to forname/newInstance, but never maps
> > directly with newInstance.
> >
> > I have a Abstract class, and I want to use a static method to retrieve
> > the requested factory. The class is not a singleton, although I
> > suppose it could be.
> >
> > Thanks for the reply,
> > iksrazal

>
>
>
> private static Map map = new HashMap();
>
> // static initializer
> static {
> map.put("class1" MyClass1.class);
> map.put("class2" MyClass2.class);
> }
>
> public static Object newObject(String type)
> {
> Class clazz = (Class)map.get(type);
> return clazz.newInstance();
> }
>
>
> You'll still have to catch a bunch of exceptions that can be thrown by
> newInstance(), but that's all there is to it. If you can't hardcode
> the class names, use Class.forName(name) as the 2nd argument in the
> put() calls, where name is a String that was read from a properties
> file.


Thanks a lot Mitch!
iksrazal


All times are GMT. The time now is 07:29 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.