Call overloaded constructors using reflection

suggest change

Example: Invoke different constructors by passing relevant parameters

import java.lang.reflect.*;

class NewInstanceWithReflection{
    public NewInstanceWithReflection(){
        System.out.println("Default constructor");
    }
    public NewInstanceWithReflection( String a){
        System.out.println("Constructor :String => "+a);
    }
    public static void main(String args[]) throws Exception {
        
        NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
        Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
        NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
        
    }
}

output:

Default constructor
Constructor :String => StackOverFlow

Explanation:

  1. Create instance of class using Class.forName : It calls default constructor
  2. Invoke getDeclaredConstructor of the class by passing type of parameters as Class array
  3. After getting the constructor, create newInstance by passing parameter value as Object array

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Reflection API:
* Call overloaded constructors using reflection

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
44 Reflection API
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap