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:



Table Of Contents