new operator is used to create objects but when you wants to create that in runtime thats no way you can use new operator. you have to use newInstance() method in this case.
// Java program to demonstrate working of newInstance()
class A { int a; }
class B { int b; }
public class Test
{
public static void fun(String c) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
Object obj = Class.forName(c).newInstance();
System.out.println("Object created for class:"
+ obj.getClass().getName());
}
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
fun("A");
}
}
Class.forName() method return class object on which we are calling newInstance() method. If the class doesn’t exist then ClassNotFoundException will occur. InstantionException will occur if the class doesn’t receive any default constructor as newInstance() method.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
new operator vs newInstance() method in Java:
new operator is used to create objects but when you wants to create that in runtime thats no way you can use new operator. you have to use newInstance() method in this case.
// Java program to demonstrate working of newInstance()
class A { int a; }class B { int b; }
public class Test
{
public static void fun(String c) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
Object obj = Class.forName(c).newInstance();
System.out.println("Object created for class:"
+ obj.getClass().getName());
}
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
fun("A");
}
}
Class.forName() method return class object on which we are calling newInstance() method. If the class doesn’t exist then ClassNotFoundException will occur. InstantionException will occur if the class doesn’t receive any default constructor as newInstance() method.