class.forName()
is a method in Java that returns the class object associated with the class or interface passed as the first parameter (i.e., name). This method is declared in the following way:
ClassLoaders are responsible for loading classes into the memory.
name − This is the fully qualified name of the desired class.
initialize − This shows that the class must be initialized.
loader − This is the class loader from which the class must be loaded.
LinkageError − occurs when the linkage fails.
ExceptionInInitializerError − occurs if the initialization provoked by this method fails.
ClassNotFoundException − occurs if the class cannot be located by the specified class loader.
The following code runs the class.forName()
method:
class ClassDemo {public static void main(String[] args) {try {Class cls = Class.forName("ClassDemo");// returns the ClassLoader objectClassLoader cLoader = cls.getClassLoader();/* returns the Class object associated with the class or interfacewith the given string name, using the given classloader. */Class cls2 = Class.forName("java.lang.Thread", true, cLoader);// returns the name of the classSystem.out.println("Class = " + cls.getName());System.out.println("Class = " + cls2.getName());}catch(ClassNotFoundException ex) {System.out.println(ex.toString());}}}
Free Resources