forName() newInstance() Methods in Java

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


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

One thought on “forName() newInstance() Methods in Java

Leave a Reply

Your email address will not be published. Required fields are marked *