forName() newInstance() Methods in Java

forName() newInstance() Methods: We have seen earlier, how to create an object without new keyword by cloning using the marker interface Cloneable. Now, Let is us see another style using forName() and newInstance() methods of class java.lang.Class.
Example on using forName() newInstance() methods to create an object without new keyword
public class Demo
  int x = 10;
  public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException
    Class myClass = Class.forName("Demo");   
    Object obj = myClass.newInstance();              
    Demo d1 = (Demo) obj;
    d1.x = 10;
    System.out.println("Object created and value is " + d1.x);	  // prints 10

forName() newInstance()
Output screenshot on forName() newInstance() in Java

forName("Demo") static method of java.lang.Class loads the .class file of Demo from hard disk into the RAM and returns a Class object; in the code it is named as myClass. myClass refers to Demo.class. forName() method throws java.lang.ClassNotFoundException. forName() method, we use mostly in JDBC to load the database driver class.

newInstance() method of class Class returns an object of Object class and is type casted in the next step to Demo d1. newInstance() method throws java.lang.InstantiationException, java.lang.IllegalAccessException.

Would you like to know all the 5 styles of creating Java object without using new keyword?

Pass your comments and suggestions to improve the tutorial on "forName() newInstance() in Java".

1 thought on “forName() newInstance() Methods in Java”

Leave a Comment

Your email address will not be published.