Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Re: Class.forname() vs clone()

Reply
Thread Tools

Re: Class.forname() vs clone()

 
 
iksrazal
Guest
Posts: n/a
 
      06-27-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) (Mitch Ratisher) wrote in message news:<(E-Mail Removed) om>...
> (E-Mail Removed) (iksrazal) wrote in message news:<(E-Mail Removed). com>...
> > (E-Mail Removed) (Mitch Ratisher) wrote in message news:<(E-Mail Removed) 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments