Updated April 10, 2023
Introduction to Java newInstance()
Java newinstance() method of class comes into the picture whenever the class needs to create a new instance dynamically. This method will be called on top of the already existing method, which is the .class name used for loading any class dynamically. This newInstance() method will be called in addition to that class for creating objects dynamically. This newInstance () method of the class does not consider any parameters or arguments from the class, which means that it doesn’t possess any constructor; thus, it can be called the no-arg constructor for one class.
Syntax
public Tsk newInstance() throws InitiationException, IllegalAccessException
The syntax flow consists of the following parameters, which represent:
- Public: Access modifier for the class being defined and declared.
- Tsk: Name of the class declared and is generic, which means it can think like an Object class and generics.
- newInstance(): Name of the method called to create and load object dynamically with addition to the .class name of the class.
- throws: keyword for catching and throwing Exceptions.
- InitiationException: followed by throws keyword, it is used for catching Exceptions which get initiated initially.
- IllegalAccessException: used for catching and accessing all the illegal or unused Exceptions.
How newInstance() method work in Java?
Any newInstance() of the class or the constructor both are called and is used for creating a new instance of the class. It is always preferred to use newInstance() method of the constructor rather than using the newInstance() method of the class because the newInstance() method of the constructor can make use of any number of arguments which is not the case with the newInstance() method of the class as the newInstance() method of the class doesn’t possess any argument which means no-arg constructor in the class. Also, sometimes it is compared and blended with the new Operator of any class.
The working flow of the newInstance() method is in this way where the new Operator is used for creating the objects, and then a decision is taken whether it is needed to create the object at run time or compile time or it is very much needed to create the object dynamically. If it is decided that the object is needed to be created at runtime, then the creation of a new Operator will be vague. Therefore, to create the object at runtime and to load the object dynamically, it is needed to create and make use of the newInstance() method.
As discussed, the newInstance() method of the class will first create an object of the class type and then be called using a .class name to create the new instance. Class.forName() method will return an object for the class, which will return the object of that class which is passed as an argument and if the class which passes the parameter does not exist, then it will throw an exception of ClassNotFoundException.
Instantiation Exception followed by throws will be called and used when the method internally calls for that class’s default constructor. IllegalAccessException will occur if there is no accessibility to the defined and specified class. Thus newInstance() method of the class is recommended because of the flexibility and versatility it provides for the creation of newInstance() of the object using dynamic loading. The typical behavior and the invocation of the constructors and object are different and enhancing as it doesn’t include any parameters to be passed to the methods and objects.
Examples of Java newInstance()
Here are the following examples mention below:
Example #1
This program is used to illustrate the Class.forName method with the newInstance method for creating the object and then print the object of that class for printing the value of the animal and creating it for the exceptions.
Code:
class Animal { int p; }
class Birds { int q; }
public class NewInstanceTst
{
public static void sounds(String s) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
Object obj_1 = Class.forName(s).newInstance();
System.out.println("Creation of newly instantiated class:"
+ obj_1.getClass().getName());
}
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
sounds("Animal");
}
}
Output:
Example #2
This program demonstrates the newInstance class of Java with passing parameters or constructors. Then it is used for dynamic allocation of the object but not used as it will throw illegal exceptions. A test class is written and executed to verify whether the instantiated class can handle the object’s dynamic loading.
Code:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class NwInstncWithconstructors {
public static void main(String[] args)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor[] constructor_a = Instnace_Constructor_Test.class.getConstructors();
Instnace_Constructor_Test animal = (Instnace_Constructor_Test)constructor_a[0].newInstance();
System.out.println(animal.content);
}
}
class Instnace_Constructor_Test {
String content;
public Instnace_Constructor_Test()
{
System.out.println("Create a new Instance:");
content = "new_instance_of_the_value";
}
}
Output:
Example #3
This program also demonstrates the newInstance class of Java. Still, without passing parameters or constructors, it is used for the dynamic allocation of objects seamlessly and makes the overall class flexible for allocation. Still, if not used, it will throw illegal exceptions. A test class is written and executed to verify whether the instantiated class can handle the object’s dynamic loading. This program calls for a no-arg method which means newInstance class directly.
Code:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class NewInstanceWithout_Constructors {
public static void main(String[] args)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor[] constructor_without_arr = Without_constructor_Test.class.getConstructors();
Without_constructor_Test sm_ob
= (Without_constructor_Test)constructor_without_arr[0]
.newInstance("one_field_value");
System.out.println(sm_ob.getthat_value());
}
}
class Without_constructor_Test {
private String that_value;
public Without_constructor_Test(String that_value)
{
this.that_value = that_value;
}
public String getthat_value()
{
return that_value;
}
public void setthat_value(String that_value)
{
this.that_value = that_value;
}
}
Output:
Conclusion
newInstance() method of java class is an added advantage as it is used to dynamically load the object without passing multiple parameters, and then it can be used with versatility within the class, and no external method is called at the run time with the help of .classForName method of the class the work gets solved relentlessly.
Recommended Articles
This is a guide to Java newInstance(). Here we discuss how the newInstance() method works in Java and examples for better understanding. You may also look at the following articles to learn more –