Skip to content
Advertisement

Dynamically loading a class in Java

I looked up the syntax and searched the api but am still confused about the process. I also searched Stackoverflow. What is the proper way to load a class and create an object out of it dynamically? In otherwords I want the user to specify what type of object they want to create, and then create that type of object. I don’t want a menu, because I want them to be able to choose any class within the current directory.

Advertisement

Answer

Assuming the class has no-arg constructor, the simplest way would be –

Object newObject = Class.forName(strFullyQualifiedClassName).newInstance();

Reference – java.lang.Class

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement