Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

what
class.forname()
method
java

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

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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());
}
}
}

RELATED TAGS

what
class.forname()
method
java
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring