What is the difference between Class.forName() and Class.forName().newInstance()?
I do not understand the significant difference (I have read something about them!). Could you please help me?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:
As explained in its javadoc, calling
Class.forName(String)returns theClassobject associated with the class or interface with the given string name i.e. it returnstest.Demo.classwhich is affected to theclazzvariable of typeClass.Then, calling
clazz.newInstance()creates a new instance of the class represented by thisClassobject. The class is instantiated as if by anewexpression with an empty argument list. In other words, this is here actually equivalent to anew Demo()and returns a new instance ofDemo.And running this
Democlass thus prints the following output:The big difference with the traditional
newis thatnewInstanceallows to instantiate a class that you don’t know until runtime, making your code more dynamic.A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don’t know anything before the runtime.
Actually, if you want to go further, have a look at Ted Neward paper Understanding Class.forName() that I was paraphrasing in the paragraph just above.
EDIT (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the DriverManager chapter of Getting Started with the JDBC API:
To register themselves during initialization, JDBC driver typically use a static initialization block like this:
Calling
Class.forName("acme.db.Driver")causes the initialization of theacme.db.Driverclass and thus the execution of the static initialization block. AndClass.forName("acme.db.Driver")will indeed "create" an instance but this is just a consequence of how (good) JDBC Driver are implemented.As a side note, I’d mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.