Re: Class.forname() vs clone()

Discussion in 'Java' started by iksrazal, Jun 27, 2003.

  1. iksrazal

    iksrazal Guest

    (Mitch Ratisher) wrote in message news:<>...
    > (iksrazal) wrote in message news:<>...
    > > (Mitch Ratisher) wrote in message news:<>...
    > > > 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
    iksrazal, Jun 27, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ahmed Moustafa

    performance of Class.forname()?

    Ahmed Moustafa, Jul 20, 2003, in forum: Java
    Replies:
    14
    Views:
    5,901
    Chris Smith
    Jul 29, 2003
  2. H.MuthuKumaraRajan

    .class and Class.forName

    H.MuthuKumaraRajan, Nov 6, 2003, in forum: Java
    Replies:
    11
    Views:
    1,726
    H.MuthuKumaraRajan
    Nov 7, 2003
  3. cyril
    Replies:
    2
    Views:
    3,857
    cyril
    Aug 25, 2004
  4. Madni
    Replies:
    1
    Views:
    5,878
  5. lordy

    To clone or not to clone..

    lordy, Jul 7, 2006, in forum: Java
    Replies:
    3
    Views:
    714
    lordy
    Jul 7, 2006
Loading...

Share This Page