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?
This question is related to
java
class
object
instantiation
Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance.
No matter how many times you call Class.forName() method, Only once the static block gets executed not multiple time:
package forNameMethodDemo;
public class MainClass {
public static void main(String[] args) throws Exception {
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
DemoClass demoClass = (DemoClass)Class.forName("forNameMethodDemo.DemoClass").newInstance();
}
}
public class DemoClass {
static {
System.out.println("in Static block");
}
{
System.out.println("in Instance block");
}
}
output will be:
in Static block
in Instance block
This in Static block
statement is printed only once not three times.
just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory
"Class.forName()" returns the Class-Type for the given name. "newInstance()" does return an instance of this class.
On the type you can't call directly any instance methods but can only use reflection for the class. If you want to work with an object of the class you have to create an instance of it (same as calling "new MyClass()").
Example for "Class.forName()"
Class myClass = Class.forName("test.MyClass");
System.out.println("Number of public methods: " + myClass.getMethods().length);
Example for "Class.forName().newInstance()"
MyClass myClass = (MyClass) Class.forName("test.MyClass").newInstance();
System.out.println("String representation of MyClass instance: " + myClass.toString());
1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:
Class.forName("Somthing");
2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:
Class.forName("Somthing").newInstance();
Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling Class.forName("ExampleClass").newInstance()
it is equivalent to calling new ExampleClass()
), on which you can call the methods that the class defines, access the visible fields etc.
In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName()
to load a JDBC driver. The JDBC driver should namely register itself in DriverManager
inside a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class MyDriver implements Driver {
static {
DriverManager.registerDriver(new MyDriver());
}
public MyDriver() {
//
}
}
Invoking Class#forName()
will execute all static initializers. This way the DriverManager
can find the associated driver among the registered drivers by connection URL during getConnection()
which roughly look like follows:
public static Connection getConnection(String url) throws SQLException {
for (Driver driver : registeredDrivers) {
if (driver.acceptsURL(url)) {
return driver.connect(url);
}
}
throw new SQLException("No suitable driver");
}
But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver
as well known example, which incorrectly registers itself inside the Constructor instead of a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class BadDriver implements Driver {
public BadDriver() {
DriverManager.registerDriver(this);
}
}
The only way to get it to work dynamically is to call newInstance()
afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance()
away.
Class.forName()
-->forName() is the static method of Class class it returns Class class object used for reflection not user class object so you can only call Class class methods on it like getMethods()
, getConstructors()
etc.
If you care about only running static block of your(Runtime given) class and only getting information of methods,constructors,Modifier etc of your class you can do with this object which you get using Class.forName()
But if you want to access or call your class method (class which you have given at runtime) then you need to have its object so newInstance method of Class class do it for you.It create new instance of the class and return it to you .You just need to type-cast it to your class.
ex-: suppose Employee is your class then
Class a=Class.forName(args[0]);
//args[0]=cmd line argument to give class at runtime.
Employee ob1=a.newInstance();
a.newInstance()
is similar to creating object using new Employee()
.
now you can access all your class visible fields and methods.
Source: Stackoverflow.com