-2

I have an array of class names:

String[] myClasses = { "Hello", "World" };

Is there a way to instantiate a class with the string names ? For example:

public SomeClassType getMyClass(String className) {
  ???
}

getMyClass("Hello"); // returns an instance of the Hello class
getMyClass("World"); // returns an instance of the World class

ps: obviously without looping through all the strings.

ps: Hello and World both extend SomeClassType

Running Turtle
  • 12,360
  • 20
  • 55
  • 73
  • Possible duplicates [here](http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java) and [here](http://stackoverflow.com/questions/7495785/java-how-to-instantiate-a-class-from-string) – Joel May 28 '14 at 15:10

3 Answers3

2

Java Reflection API:

String className = "MyClass";
Class<?> myClass = Class.forName(className);
MyClass ob = (MyClass) myClass.newInstance();
martinez314
  • 12,162
  • 5
  • 36
  • 63
2

You can use Class#forName to obtain a Class type, and later use clazz.newInstance() to get a Instance of the class.

The problem is that you need the full qualifier name (the name of the class and the package), if you dont have the full name, you can use Reflection to get iterate the packages and obtain the class you want.

You can see a working example here

Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40
0

Take a look at the Java reflection tutorial (http://docs.oracle.com/javase/tutorial/reflect/class/index.html). Here is an example:

public class Hello {

    public void foo() {
        System.out.println("Inside Hello foo()...");
    }

    public static void main(String[] args) {
        Class<?> c;
        try {
            c = Class.forName("Hello");
            Hello h = (Hello) c.newInstance();
            h.foo();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
Edwin Torres
  • 2,774
  • 1
  • 13
  • 15