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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

How can I send arguments to the constructor?
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().
newInstance() is deprecated now, replaced with clazz.getDeclaredConstructor().newInstance()
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;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.