20

If I have 2 classes, "A" and "B", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}

Thanks!

Joel

Joel
  • 5,949
  • 12
  • 42
  • 58

2 Answers2

25
Class c= Class.forName(className);
return c.getDeclaredConstructor().newInstance();//assuming you aren't worried about constructor .

For invoking constructor with argument

 public static Object createObject(Constructor constructor,
      Object[] arguments) {

    System.out.println("Constructor: " + constructor.toString());
    Object object = null;

    try {
      object = constructor.newInstance(arguments);
      System.out.println("Object: " + object.toString());
      return object;
    } catch (InstantiationException e) {
      //handle it
    } catch (IllegalAccessException e) {
      //handle it
    } catch (IllegalArgumentException e) {
      //handle it
    } catch (InvocationTargetException e) {
      //handle it
    }
    return object;
  }
}

have a look

boardtc
  • 1,304
  • 1
  • 15
  • 20
jmj
  • 237,923
  • 42
  • 401
  • 438
  • How can I send arguments to the constructor? – Joel Jan 22 '11 at 09:36
  • 2
    `System.out.println(e);` Please, NEVER! Why don't you simply declare the exception? When you *really* feel like being able to handle it by reporting, use `e.printStackTrace()`. – maaartinus Jan 22 '11 at 10:10
  • newInstance() is deprecated now, replaced with clazz.getDeclaredConstructor().newInstance() – boardtc Oct 01 '21 at 21:06
5

You may take a look at Reflection:

import java.awt.Rectangle;

public class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928