Create new object from a string in Java
Is there a way to create a new class from a String variable in Java?
String className = "Class1";
//pseudocode follows
Object xyz = new className(param1, param2);
Also, if possible does the resulting object have to be of type Object?
There may be a better way, but I want to be able to retrieve values from an XML file, then instantiate the classes named after those strings. Each of these classes implement the same interface and are derived from the same parent class, so I would then be able to call a particular method in that class.
This is what you want to do:
String className = "Class1";
Object xyz = Class.forName(className).newInstance();
Note that the newInstance method does not allow a parametrized constructor to be used. (See Class.newInstance documentation)
If you do need to use a parametrized constructor, this is what you need to do:
import java.lang.reflect.*;
Param1Type param1;
Param2Type param2;
String className = "Class1";
Class cl = Class.forName(className);
Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class);
Object xyz = con.newInstance(param1, param2);
See Constructor.newInstance documentation
Yes, you can load a class on your classpath given the String name using reflection, using Class.forName(name), grabbing the constructor and invoking it. I'll do you an example.
Consider I have a class:
com.crossedstreams.thingy.Foo
Which has a constructor with signature:
Foo(String a, String b);
I would instantiate the class based on these two facts as follows:
// Load the Class. Must use fully qualified name here!
Class clazz = Class.forName("com.crossedstreams.thingy.Foo");
// I need an array as follows to describe the signature
Class[] parameters = new Class[] {String.class, String.class};
// Now I can get a reference to the right constructor
Constructor constructor = clazz.getConstructor(parameters);
// And I can use that Constructor to instantiate the class
Object o = constructor.newInstance(new Object[] {"one", "two"});
// To prove it's really there...
System.out.println(o);
Output:
com.crossedstreams.thingy.Foo@20cf2c80
There's plenty of resources out there which go into more detail about this, and you should be aware that you're introducing a dependency that the compiler can't check for you - if you misspell the class name or anything, it will fail at runtime. Also, there's quite a few different types of Exception that might be throws during this process. It's a very powerful technique though.
This should work:
import java.lang.reflect.*;
FirstArgType arg1;
SecondArgType arg2;
Class cl = Class.forName("TheClassName");
Constructor con = cl.getConstructor(FirstArgType.class, SecondArgType.class);
Object obj = con.newInstance(arg1, arg2);
From there you can cast to a known type.
This worked a little more cleanly for me in JDK7, while the answers above made things a bit more difficult than they needed to be from a newbie perspective: (assumes you've declared 'className' as a String variable passed as a method parameter or earlier in the method using this code):
Class<?> panel = Class.forName( className );
JPanel newScreen = (JPanel) panel.newInstance();
From this point you can use properties / methods from your dynamically-named class exactly as you would expect to be able to use them:
JFrame frame = new JFrame(); // <<< Just so no-one gets lost here
frame.getContentPane().removeAll();
frame.getContentPane().add( newScreen );
frame.validate();
frame.repaint();
The examples in other answers above resulted in errors when I tried to .add() the new 'Object' type object to the frame. The technique shown here gave me a usable object with just those 2 lines of code above.
Not exactly certain why that was - I'm a Java newbie myself.