-2

I'm wondering how I can create a new object of a certain class, if I have that classname saved in a string.

eg. I imagine to create an object of FooClass it would be something like:

String className = "FooClass";
className.toClass() newObject = new (className.toClass())(); 

I've done quite a bit of searching but have been unable to find an answer.

Thanks

Jordan Andrews
  • 163
  • 3
  • 16
  • This is known as reflection. – Sotirios Delimanolis Sep 27 '14 at 05:37
  • However, this isn't very useful without using an appropriate unifying Interface (or Supertype, if you still believe in Subtype/LSP polymorphism). Otherwise you just get an Object which is really lame to play with - to be used "as" the created type, an Object expression must either itself be used with more reflection (not fun) or *cast* to an appropriate type (which largely goes back to the original problem). The Types of Expressions, including variables, *must* be resolved during compilation. Generics and Interfaces can help. – user2864740 Sep 27 '14 at 05:39

1 Answers1

3

As said in Oracle Documentation you can do it in the following way:

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

Let me to provide a very simple example of such using:

Suppose we have that Main class and the class we need to instanciate are in the same package. Then we can act as follows:

The class we need to instanciate:

public class MyClass {
    public int myInt;
    public MyClass(Integer myInt){
        this.myInt = myInt;
    }
}

main method:

public static void main(String[] args) throws Exception {
    //Class name must contain full-package path
    // e.g. "full.pack.age.classname"
    String className = Main.class.getPackage().getName() + ".MyClass"; 
    Class<?> clazz = Class.forName(className); 

    //Class.getConstructor(Class<?> ... parameters) gives you a suitable constructor
    //depends on the argument types you're going to pass to them.                                                                  
    Constructor<?> ctor = clazz.getConstructor(Integer.class); 

    //Object creation and constructor call
    Object object = ctor.newInstance(new Object[] { 1 }); //1 is just myInt value passes to a contructor being invoked.
    System.out.println(((MyClass) object).myInt); //Prints 1
}