I have read this article : Construct Object using class name and now I know how to do this:
MySuperClass mClass = new MySuperClass();
<=>
Class<?> MyClass = Class.forName("MySuperClass");
MySuperClass mClass = MyClass.newInstance();
They are equivalent, right?
But now there is a problem. The user clicks on the List of class names and I should create an object of that class at runtime. Say these classes are all subclasses of MySuperClass. So could anyone please tell me how I can do this with Class.forName?
MySuperClass mClass = new ...(); // The subclass name in place of "..." can be determined at runtime.
Or this?
... mClass = new ...(); // The subclass name in place of "..." can be determined at runtime.
You had the right idea going with the whole Class.forName thing.
For the MySuperClass mClass = new ...(); code, lets assume that you have the name stored in a String, and let us call it className.
Class<?> subClass = Class.forName(className);
MySuperClass mClass = (MySuperClass) subClass.newInstance();
Note that className can also have packages as shown in Is there a way to instantiate a class by name in Java?
As you can see, the code is very similar to what you had before, except you just had to cast the subclass to the super class. Alternatively, you could set it as an Object, but with limited functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With