The newInstance() method of a Constructor class is used to create and initialize a new instance of this constructor, with the initialization parameters passed as parameter to this method. Each parameter is unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.
If the number of formal parameters of the constructor is 0, the supplied parameter is of length 0 or null. If the constructor completes normally, returns the newly created and initialized instance.
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
Parameters: This method accepts initargs as the parameter which is an array of objects to be passed as arguments to the constructor call. The values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. float in Float).
Return value: This method returns a new object created by calling the constructor this object represents.
Exception: This method throws following Exceptions:
- IllegalAccessException: if this Constructor object is enforcing Java language access control and the underlying constructor is inaccessible.
- IllegalArgumentException: if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if this constructor pertains to an enum type.
- InstantiationException: if the class that declares the underlying constructor represents an abstract class.
- InvocationTargetException: if the underlying constructor throws an exception.
- ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate the newInstance() method:
New Instance is created New Instance
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.