Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading a class in Java

Tags:

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.

like image 367
rubixibuc Avatar asked Apr 06 '11 18:04

rubixibuc


People also ask

What is a dynamic class in Java?

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.

What is static and dynamic class loading in Java?

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.

Is it possible to load a class by two ClassLoader?

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.


1 Answers

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

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

Reference - java.lang.Class

like image 97
Amol Katdare Avatar answered Nov 29 '22 20:11

Amol Katdare