It can be done, using the Reflection API:
Class<?> klazz = Class.forName("javax.swing.JPanel");
JPanel panel = (JPanel) klazz.newInstance();
Notice that you have to pass a fully-qualified class name to the forName()
method, and that at some point (be it as a type parameter to Class<?>
or by using a cast like in the above code) you'll have to explicitly specify the class that you intend to instantiate. Or if you don't care about the exact type of the instance, you can simply do this:
Object obj = klazz.newInstance();
Also, I'm assuming that the class has defined a no-arguments constructor. If that is not the case, you'll have to create a Constructor
object first before instantiating the new object:
Class<?> klazz = Class.forName("javax.swing.JPanel");
Constructor<?> constructor = klazz.getDeclaredConstructor(/* parameter types */);
JPanel panel = (JPanel) constructor.newInstance();