Tag Archives: Class.ForName

Difference between Class.forName() and ClassLoader.loadClass()

Class.forName() and System.ClassLoader.loadClass() having big difference in context of loading class. You can understand it better by below examples

Class.forName() and System.ClassLoader.loadClass() Difference

Class.forName(“ClassName”)  :

  • Internally class ClassLoader.loadClass() that loaded the class.
  • It Initialize the class by using all static blocks in class.
  • In ClassLoader subsystem it executes all the three phases load, link and initialize phases.

For Example : In JDBC we use Class.forName(“Driver Name”) to load SQL Driver and register it.

ClassLoader.getSystemClassLoader().loadClass(“ClassName”):

  • Use system class Loader which is overridable to load class.
  • loadClass() method does not initialize the class. Class only will initialize when used for the first time.
  • in class loader subsystem loadClass() executes on two phases i.e load and link phases.

For Example : if we use ClassLoader.loadClass() method to load JDBC driver then only will load driver class but it will not register.

In below Java code you will understand how both ways of loading class are different because for same MyExampleClass, Class.forName() is intializing and  printing static block content while ClassLoader.getSystemClassLoader().loadClass() will only load the class and not initialize that’s why not printing anything in console.

public class MyExampleClass {
	    static {
	        System.out.println("Static Block in MyExampleClass");
	    }
}

public class ExampleLoader {

	public static void main(String[] args) {
		try {
			System.out.println("==========Result of Class.forName()===========");
			Class.forName("MyExampleClass");

			System.out.println("==========Result of ClassLoader.getSystemClassLoader().loadClass()===========");
			ClassLoader.getSystemClassLoader().loadClass("MyExampleClass");
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}

	}

}

Output :

==========Result of Class.forName()===========
Static Block in MyExampleClass
==========Result of ClassLoader.getSystemClassLoader().loadClass()===========

Summary:

  • Explained about difference between loading of class for both methods  Class.forName() and ClassLoader.loadClass().
  • Loader sub systems phases cover in both the case.
  • Example of Class.forName() and ClassLoader.loadClass().

[Solved] ClassNotFoundException: com.mysql.jdbc.Driver

java.lang.ClassNotFoundException is Checked Exception which is subclass of  java.lang.ReflectiveOperationException. This  is thrown when application load a class by String name whose definition is not found. This exception occurs by below methods :

  • The forName method in the class Class.

                 Class.forName(java.lang.String)

  • The findSystemClass method in the class ClassLoader.

                ClassLoader.findSystemClass()

  • The loadClass method in class ClassLoader.

                ClassLoader.loadClass(java.lang.String, boolean)

 Difference between Class.forName() and ClassLoader.loadClass()

Example 1: ClassNotFoundException

Below is example of connecting with database and retrieve data from sql table. This will throw ClassNotFoundException because sql driver jar is not in classpath. After this example also mentioned solution.

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ClassNotFoundException1 {

	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");

			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/university", "root", "");

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select name from employee");
			String dbtime;
			while (rs.next()) {
				dbtime = rs.getString(1);
				System.out.println(dbtime);
			}

			con.close();

		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
		}

	}

}

Output:

Connection Failed! Check output console
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Unknown Source)
	at example.ClassNotFoundException1.main(ClassNotFoundException1.java:13)

Solutions:

For solving ClassNotFoundException by Class.ForName() method  considering above example to load MySQL driver same way you can follow for other classes and different DB drivers.

Solution in Eclipse :Follow below steps :

  • Right click your project folder and open up Properties.
  • From the right panel, select Java Build Path then go to Libraries tab.
  • Select Add External JARs to import the MySql driver.
  • From the right panel, select Deployment Assembly.
  • Select Add…, then select Java Build Path Entries and click Next.
  • You should see the SQL driver on the list. Select it and click first.

Tomcat :

If directly running from tomcat.Just copy the MySql-Connector.jar into Tomcat’s lib folder/directory, and then remove the jar from the webApp’s lib folder, and then, run the project.

Summary :

  • Define what is ClassNotFoundException.
  • What are methods throws ClassNotFoundException?
  • Example for ClassNotFoundException.
  • How to fix ClassNotFoundException in Eclipse and Tomcat.