I have been trying to understand the difference between using new
to instantiate an object vs using Class.forName("A").newInstance();
.
I have run the following code for a simple class A
which shows using Class.forname("A").newInstance()
is 70-100 times slower than using just new A()
.
I am curious to know why there is such a difference in time, but couldn't figure out. Please someone help me to understand the reason.
public class Main4test {
public Main4test() {
}
static int turns = 9999999;
public static void main(String[] args) {
new Main4test().run();
}
public void run() {
System.out.println("method1: " + method1() + "");
System.out.println("method2:" + method2() + "");
}
public long method2() {
long t = System.currentTimeMillis();
for (int i = 0; i < turns; i++) {
try {
A a = (A) Class.forName("A").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return System.currentTimeMillis() - t;
}
public long method1() {
long t = System.currentTimeMillis();
for (int i = 0; i < turns; i++) {
try {
A a = new A();
} catch (Exception e) {
e.printStackTrace();
}
}
return System.currentTimeMillis() - t;
}
}
public class A {
int a;
public A() {
a=0;
}
}
Class. newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException .
forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.
Class. forName - It will load the Test class and return the Class class object which contains the metadata of Test class Like name, package, constructor, annotations, methods, fields. newInstance() - Used to instantiate new objects using Java Reflection.
A a = new A();
Calls the new
operator and the constructor of A
directly, where A
is mentioned in the source text and has therefore already been loaded and initialized.
A a = (A) Class.forName("A").newInstance();
A
has already been loadednew
operator and the no-args constructor via reflectionA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With