Tuesday, June 14, 2011
Sunday, June 5, 2011
“Class.forName()” and “Class.forName().newInstance()”
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 the Class object associated with the class or interface with the given string name i.e. it returns test.Demo.class which is affected to the clazz variable of type Class .
Then, calling
clazz.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. In other words, this is here actually equivalent to a new Demo() and returns a new instance of Demo .
And running this
Demo class thus prints the following output:
The big difference with the traditional
new is that newInstance allows 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 the acme.db.Driver class and thus the execution of the static initialization block. And Class.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 and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.
|
123passportphoto is a very easy to use passport photo website that provides six enhanced photos. I have never had an issue while using this ...
-
Effective October 31, 2014, Embassy Kingston does not accept interview applications from third country nationals Effective October...
-
Introduction/ History of Struts The first version of Struts was released in June 2001. It was born out of the idea that JSPs and servle...
-
Cloudera Hadoop Offers: § HDFS – Self healing distributed file system § MapReduce – Powerful, parallel data processing framew...