sneppets-java8

When to use java.lang.Class, forName() and newInstance() difference?

This tutorial guides you on how to use java.lang.Class, forName() and newInstance() methods with examples. 

java.lang.Class class, forName() and newInstance() difference

It is one of the most important class in Java and it provides utility methods like getClass(), getName(), forName() and newInstance() methods. Class has no public constructor and JVM creates a java.lang.Class objects automatically every time when the classes are loaded.

You might have used Class.forName() in JDBC programs to load Oracle or MySQL drivers as shown below.

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sneppets","mysql","mysql");
stm=con.createStatement();

The following example uses a Class Object to print the class name of the object. In which we have used getClass() and getName() methods.

private static void printClassName(Object obj) {

    System.out.println("The class of " + obj + " is " + obj.getClass().getName());
		
}

The following code is the complete example which demonstrates the usage of java.lang.Class class and it’s utility methods mentioned above.

package com.sneppets.javalang;

class Person {
	
	String name;
	
	int age;
	
	public Person(String name, int age){
		
		this.name = name;
		this.age = age;
	}
}


public class ClassExample {
	
	public ClassExample() {
		
		System.out.println("Class Demo Example");
	}
	
	public static void main (String[] args) {
		
		Person p1 = new Person("Peter", 40);
		Person p2 = new Person("John", 25);
		
		//getClass()
		compareClassObjects(p1,p2);
		
		//getName()
		printClassName(p1);
		
		//forName() and newInstance()
                Class c;
		try {
			c = Class.forName("com.sneppets.javalang.ClassExample");
			ClassExample ce = (ClassExample) c.newInstance();
		} catch (ClassNotFoundException | InstantiationException | 
				IllegalAccessException e) {
			e.printStackTrace();
		}       
        
	}


	private static void compareClassObjects(Object obj1, Object obj2) {
		
		if(obj1.getClass() == obj2.getClass()) {
			System.out.println("obj1 and obj2 are instances of the same class");
		} else {
			System.out.println("obj1 and obj2 are instances of different classes");
		}
 		
	}

	
	private static void printClassName(Object obj) {
		System.out.println("The class of " + obj +
                " is " + obj.getClass().getName());
		
	}

}

Output

obj1 and obj2 are instances of the same class
The class of com.sneppets.javalang.Person@6f75e721 is com.sneppets.javalang.Person
Class Demo Example

Difference between Class.forName() and Class.newInstance()

Class.forName() returns the Class object associated with the class or interface with the given string name i.e. it returns com.sneppets.javalang.ClassExample class and the reference c of type Class refer to that Class object.

Class c = Class.forName("com.sneppets.javalang.ClassExample");

Then, calling c.newInstance() will create a new instance of the class represented by that Class object. The class is instantiated as if by a new expression with an empty argument list. In simple words, it is equivalent to new ClassExample().

ClassExample ce = (ClassExample) c.newInstance();

Note, Class.newInstance() is the backbone of Java Reflection which allows you to create an instance of class without new operator as shown above. This way of creating objects is quite powerful and can be very useful.

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments