Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I instantiate an object with Class.forName and convert it to the right type?

Tags:

java

class

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.
like image 410
nomnom Avatar asked Feb 03 '26 18:02

nomnom


1 Answers

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.

like image 90
Vineet Kosaraju Avatar answered Feb 05 '26 06:02

Vineet Kosaraju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!