Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance from String in Java

Tags:

java

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

like image 703
Joel Avatar asked Jan 22 '11 09:01

Joel


People also ask

How are instances created in string class?

You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance. The '+' operator is overloaded to concatenate two String operands. '+' does not work on any other objects such as Point and Circle . String is immutable.


2 Answers

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

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

like image 165
jmj Avatar answered Sep 30 '22 12:09

jmj


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;
   }
}
like image 33
Darin Dimitrov Avatar answered Sep 30 '22 12:09

Darin Dimitrov