What is the class.forName() method in Java?

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:​

svg viewer

ClassLoaders are responsible for loading classes into the memory.

Parameters

  • 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.

Exceptions

  • 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.

Implementation

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 object
ClassLoader cLoader = cls.getClassLoader();
/* returns the Class object associated with the class or interface
with the given string name, using the given classloader. */
Class cls2 = Class.forName("java.lang.Thread", true, cLoader);
// returns the name of the class
System.out.println("Class = " + cls.getName());
System.out.println("Class = " + cls2.getName());
}
catch(ClassNotFoundException ex) {
System.out.println(ex.toString());
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved