java.lang.Class
is a class in java, it represents classes and interfaces in a running Java application.
objects created using newInstance()
method will call the default constructor of the class.
Creates a new instance of the class represented by this Class object. The newInstance method of the Class class is used to create an object.
package org.wesome.dsalgo.design.pattern;
public class Apple {
String name = "McIntosh";
public static void main(String[] args) {
try {
Class classObj = Class.forName("org.wesome.dsalgo.design.pattern.Apple");
Apple apple = (Apple) classObj.newInstance();
System.out.println("apple = " + apple.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The newInstance
method will call the default constructor
of the class.
package org.wesome.dsalgo.design.pattern;
public class Apple {
String name = "McIntosh";
public Apple() {
System.out.println("Apple default constructor");
}
public Apple(String name) {
System.out.println("Apple parameterized constructor");
this.name = name;
}
public static void main(String[] args) {
try {
Class classObj = Class.forName("org.wesome.dsalgo.design.pattern.Apple");
Apple apple = (Apple) classObj.newInstance();
System.out.println("apple = " + apple.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
New Instance with Exception
The newInstance
by default calls the default constructor
of the class, if the constructor
throws an Exception
while creating an object, the newInstance
will create the object, but if creating an object using new keyword
will fail.
package org.wesome.dsalgo.design.pattern;
public class Apple {
String name = "McIntosh";
public Apple() throws Exception {
System.out.println("Apple default constructor");
throw new Exception();
}
public static void main(String[] args) {
try {
Class classObj = Class.forName("org.wesome.dsalgo.design.pattern.Apple");
Apple apple = (Apple) classObj.newInstance();
System.out.println("apple = " + apple.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}