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.
Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.
The major difference between static and dynamic class loading is that in static loading retrieval of class definition and instantiation of the object is done at compile time, while in dynamic loading classes are loaded at run time using Class.
A class is always identified using its fully qualified name (package. classname). So when a class is loaded into JVM, you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.
Assuming the class has no-arg constructor, the simplest way would be -
Object newObject = Class.forName(strFullyQualifiedClassName).newInstance();
Reference - java.lang.Class
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